实例:生产罐头工厂

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();

 

相关文章:

  • 2021-07-03
  • 2022-01-04
  • 2021-07-16
  • 2021-08-02
  • 2021-11-11
  • 2022-12-23
  • 2021-06-03
猜你喜欢
  • 2021-06-23
  • 2021-10-03
  • 2021-11-12
  • 2021-09-28
  • 2021-11-29
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案