简单工厂模式

…衆ロ難τιáo~ 提交于 2019-11-29 01:35:11

 

 

 1 namespace UnitTestProject1
 2 {
 3 
 4     /// <summary>
 5     /// 简单工厂模式的缺点:
 6     /// 增加具体产品时,需要修改工厂类里面生成具体产品的方法,这就违反了开闭原则。具体产品经常发生变化时,不建议使用简单工厂模式。
 7     /// 
 8     /// </summary>
 9     [TestClass]
10     public class simpleDesign
11     {
12         [TestMethod]
13         public void TestMethod1()
14         {
15             IPeople people = new PeopleFactory().NewInstance(1);
16             people.SayHello();
17         }
18     }
19 
20     public interface IPeople
21     {
22         void SayHello();
23     }
24 
25     public class ChinesePeople : IPeople
26     {
27         public void SayHello()
28         {
29             Console.WriteLine("早上好,吃了吗");
30         }
31     }
32 
33     public class EnglandPeople : IPeople
34     {
35         public void SayHello()
36         {
37             Console.WriteLine("hello?");
38         }
39     }
40 
41     public class PeopleFactory
42     {
43 
44         public IPeople NewInstance(int witch)
45         {
46             IPeople people = null;
47             switch (witch)
48             {
49                 case 1:
50                     people = new ChinesePeople();
51                     break;
52                 case 2:
53                     people = new EnglandPeople();
54                     break;
55             }
56             return people;
57         }
58 
59     }
60 }

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!