工厂方法
前面我们学习了简单工厂,发现一个问题就是简单工厂集合了矛盾,为了解决这个问题我们针对每一种产品提供一个工厂类。通过不同的工厂实例来创建不同的产品实例。在同一等级结构中,支持增加任意产品这种设计模式就是工厂方法。
优点:允许系统在不修改具体工厂角色的情况下引进新产品
缺点:由于每加一个产品,就需要加一个产品工厂的类,增加了额外的开发量

1 public interface IFactory
2 {
3 IRace CreateRace();
4 }

1 public class HumanFactory : IFactory
2 {
3 public virtual IRace CreateRace()
4 {
5 return new Human();
6 }
7 }
8 public class HumanFactoryAdvanced: HumanFactory
9 {
10 public override IRace CreateRace()
11 {
12 Console.WriteLine("123");
13 return new Human();
14 }
15 }

1 public class NEFactory : IFactory
2 {
3 public IRace CreateRace()
4 {
5 return new NE();
6 }
7 }

1 public class ORCFactory : IFactory
2 {
3 public IRace CreateRace()
4 {
5 return new ORC();
6 }
7 }

1 public class UndeadFactory : IFactory
2 {
3 public IRace CreateRace()
4 {
5 return new Undead();
6 }
7 }
前端调用

1 {
2 Human human = new Human();//1 到处都是细节
3 }
4 {
5 IRace human = new Human();//2 左边是抽象 右边是细节
6 }
7 {
8 //human.
9 IFactory factory = new HumanFactory();//包一层
10 IRace race = factory.CreateRace();
11 //何苦 搞了这么多工厂 还不是创建个对象
12 //以前依赖的是Human 现在换成了HumanFactory
13
14 //1 工厂可以增加一些创建逻辑 屏蔽对象实例化的复杂度
15 //2 对象创建的过程中 可能扩展(尤其是ioc)
16 }
17 {
18 //Undead
19 IFactory factory = new UndeadFactory();
20 IRace race = factory.CreateRace();
21 }
工厂方法:把简单工厂拆分成多个工厂,保证每个工厂的相对稳定
但是要多new一次工厂? 难免,中间层,屏蔽业务类变化的影响,而且可以留下创建对象的扩展空间=>eg:HumanFactoryAdvanced 在创建对象之前执行一些操作
开闭原则:对扩展开发,对修改封闭
工厂方法完美遵循了开闭原则
工厂方法的好处就是对于拓展很方便例如增加第五种族

1 /// <summary>
2 /// 比如构造很复杂。。比如依赖其他对象
3 /// 屏蔽变化
4 /// </summary>
5 public class FiveFactory : IFactory
6 {
7 public virtual IRace CreateRace()
8 {
9
10 //return new Five();
11 return new Five(2, "New", 2);
12 }
13 }
前端调用

1 {
2 IRace five = new Five();//修改
3 }
4
5 {
6 //five
7 IFactory factory = new FiveFactory();
8 IRace race = factory.CreateRace();
9 }
