创建型设计模式之-工厂模式

先看代码:

 1  public class Facebook
 2     {
 3         static void Main()
 4         {
 5             FactoryCreateStudent factoryCreateStudent = new ChinaFactory();
 6             IStudent iStudent= factoryCreateStudent.CreateStudent();
 7             //为什么把普普通通的类的new弄这么麻烦
 8             //创建对象的接口,让子类决定具体实例化的对象,把简单的内部逻辑移动更前面的调用端,很好扩展,
 9             //工厂方法克服了简单工厂所违背的的开闭原则的缺点,扩展性高,易于维护,想要增加一个产品,只需要增加一个工厂类即可。
10             //不像工厂方法,还得修改工厂里面的方法。而添加工厂类就可以实现开闭原则,就是不动源码
11 
12         }
13     }
14     #region 学生接口于实现类
15     public interface IStudent
16     {
17         void Study();
18     }
19     public class ChinaStudent: IStudent
20     {
21         public void Study()
22         {
23             Console.WriteLine("中国学生在学习");
24         }
25     }
26     public class AmericanStudent : IStudent
27     {
28         public void Study()
29         {
30             Console.WriteLine("美国学生在学习");
31         }
32     }
33     public class KoreanStudent : IStudent
34     {
35         public void Study()
36         {
37             Console.WriteLine("韩国学生在学习");
38         }
39     }
40     #endregion
41     #region 工厂创建具体的业务类
42     public interface FactoryCreateStudent
43     {
44         IStudent CreateStudent();
45     }
46 
47     public class ChinaFactory : FactoryCreateStudent
48     {
49         public IStudent CreateStudent()
50         {
51             return new ChinaStudent();
52         }
53     }
54     public class AmericanFactory : FactoryCreateStudent
55     {
56         public IStudent CreateStudent()
57         {
58             return new AmericanStudent();
59         }
60     }
61     public class KoreanFactory : FactoryCreateStudent
62     {
63         public IStudent CreateStudent()
64         {
65             return new KoreanStudent();
66         }
67     }
68     #endregion
View Code

为什么把普普通通的类的new弄这么麻烦
创建对象的接口,让子类决定具体实例化的对象,把简单的内部逻辑移动更前面的调用端,很好扩展,
工厂方法克服了简单工厂所违背的的开闭原则的缺点,扩展性高,易于维护,想要增加一个产品,只需要增加一个工厂类即可。
不像工厂方法,还得修改工厂里面的方法。而添加工厂类就可以实现开闭原则,就是不动源码

本文来自博客园,作者:小换哥,转载请注明原文链接:https://www.cnblogs.com/haunge/p/15035062.html

原文地址:https://www.cnblogs.com/haunge/p/15035062.html