07-简单工厂(不属于设计模式)
1. 简介
严格意义上的说,简单工厂不属于23中设计模式,这里抛砖引玉,引出后面的工厂方法和抽象工厂两种设计模式。
简答工厂违背:单一职责原则、开闭原则、迪米特法则。
2. 核心代码
1 /// <summary> 2 /// 简单工厂类 3 /// </summary> 4 public class simpleFactory 5 { 6 public static IPeople CreateInstance(PeopleKind kind) 7 { 8 IPeople iPeople = null; 9 switch (kind) 10 { 11 case PeopleKind.Chinese: 12 { 13 iPeople = new Chinese(); 14 break; 15 } 16 case PeopleKind.Janpanese: 17 { 18 iPeople = new Janpanese(); 19 break; 20 } 21 case PeopleKind.America: 22 { 23 iPeople = new America(); 24 break; 25 } 26 } 27 return iPeople; 28 } 29 30 //复习 反射+简单工厂+配置文件(IOC) http://www.cnblogs.com/yaopengfei/p/6891286.html 31 32 public enum PeopleKind 33 { 34 Chinese=0, 35 Janpanese=1, 36 America=2 37 } 38 39 }
1 static void Main(string[] args) 2 { 3 //满足依赖倒置原则 4 IPeople iPeople1 = simpleFactory.CreateInstance(simpleFactory.PeopleKind.Chinese); 5 IPeople iPeople2 = simpleFactory.CreateInstance(simpleFactory.PeopleKind.America); 6 IPeople iPeople3 = simpleFactory.CreateInstance(simpleFactory.PeopleKind.Janpanese); 7 iPeople1.Eating(); 8 iPeople2.Eating(); 9 iPeople3.Eating(); 10 Console.ReadKey(); 11 }