1. 简介
工厂方法:符合依赖倒置原则、单一职责、开闭原则。
与简单工厂的区别:简单工厂是在一个工厂里生成多个不同的类,而工厂方法是一个对象对应一个生成工厂,这些工厂都实现了一个共同的接口IFactory,很好的符合了依赖倒置原则、单一职责、开闭原则, 每个工厂只负责创建对象。
2. 核心代码
1 public interface IFactory 2 { 3 IPeople CreateInstance(); 4 }
1 public class ChineseFactory : IFactory 2 { 3 public IPeople CreateInstance() 4 { 5 return new Chinese(); 6 } 7 }
1 public class JanpaneseFactory : IFactory 2 { 3 public IPeople CreateInstance() 4 { 5 return new Janpanese(); 6 } 7 }
1 public class AmericaFactory : IFactory 2 { 3 public IPeople CreateInstance() 4 { 5 return new America(); 6 } 7 }
1 static void Main(string[] args) 2 { 3 IFactory iFactory1 = new ChineseFactory(); 4 IFactory iFactory2 = new AmericaFactory(); 5 IFactory iFactory3 = new JanpaneseFactory(); 6 7 IPeople iPeople1 = iFactory1.CreateInstance(); 8 IPeople iPeople2 = iFactory2.CreateInstance(); 9 IPeople iPeople3 = iFactory3.CreateInstance(); 10 11 12 iPeople1.Eating(); 13 iPeople2.Eating(); 14 iPeople3.Eating(); 15 16 Console.ReadKey(); 17 18 }