工厂方法模式

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace DesignPattern.CreationalPatern
 8 {
 9     #region 工厂方法模式要点
10 
11     //定义抽象工厂,将创建具体对象的过程推迟到其具体工厂中进行;
12     //具体工厂必须实现的抽象接口,系统就可以再不修改工厂类逻辑的情况下来添加新产品。
13     //主要遵循开放封闭原则,依赖倒转原则
14 
15     #endregion
16     public abstract class FactoryMethodPattern
17     {
18         public abstract Food MakeFood();
19     }
20 
21     //在工厂方法模式中,工厂类与具体产品类具有平行的等级结构,它们之间是一一对应的。
22     public class IceCreamFactory : FactoryMethodPattern
23     {
24         public override Food MakeFood()
25         {
26             return new IceCream();
27         }
28     }
29 
30     public class CakeFactory : FactoryMethodPattern
31     {
32         public override Food MakeFood()
33         {
34             return new Cake();
35         }
36     }
37 
38     /************************************需要创建的对象****************************************/
39 
40     public abstract class Food
41     {
42         public abstract void PrintName();
43     }
44 
45 
46     public class IceCream : Food
47     {
48         public override void PrintName()
49         {
50             Console.WriteLine("冰激凌");
51         }
52     }
53 
54     public class Cake : Food
55     {
56         public override void PrintName()
57         {
58             Console.WriteLine("蛋糕");
59         }
60     }
61 
62 }

 

posted on 2021-06-25 11:37  HowieGo  阅读(40)  评论(0)    收藏  举报

导航