设计模式-工厂模式(一)

实例:生产罐头工厂

1.罐头实例类

public class ThinCan
    {
        public string name { get; set; }

        public DateTime factorydate { get; set; }


        public virtual void Show()
        {
            Console.WriteLine("我是一个" + name + "罐头,我得出厂日期为" + factorydate + "");
        }
    }

2.苹果罐头

  public  class AppleThinCan:ThinCan
    {
        public override void Show()
        {
            ShowApple();
            base.Show();
        }

        public void ShowApple()
        {
            Console.WriteLine("我是AppleThinCan类");
        }
    }

3.香蕉罐头

public class BananaThinCan:ThinCan
    {
        public override void Show()
        {
            ShowBanana();
            base.Show();
        }
        public void ShowBanana()
        {
            Console.WriteLine("我是BananaThinCan类");
        }
    }

4.橘子罐头

 public class OrangeThinCan:ThinCan
    {
        public override void Show()
        {
            ShowOrange();
            base.Show();
        }
        public void ShowOrange()
        {
            Console.WriteLine("我是ShowOrange类");
        }
    }

5.罐头工厂

  public class ThinCanFactory
    {
        public static ThinCan CreateFactory(string name)
        {
            ThinCan tc = null;
            switch (name)
            {
                case "Apple": tc=new AppleThinCan(); break;
                case "Banana":tc=new BananaThinCan();break;
                case "Orange":tc=new OrangeThinCan();break;
                default:break;
            }
            return tc;
        }
    }

6.调用

            ThinCan tc = null;
            tc = ThinCanFactory.CreateFactory("Apple");
            tc.name = "苹果";
            tc.factorydate = DateTime.Now;
            tc.Show();

 

posted @ 2019-12-23 10:15  萌橙  阅读(169)  评论(0编辑  收藏  举报