抽象工厂模式
有工厂模式引出抽象工厂模式,先看工厂模式实例代码:
public abstract class Product { public abstract void work(); } public class ProductA : Product { public override void work() { Console.Write("ProductA"); } } public class ProductB : Product { public override void work() { Console.Write("ProductB"); } } public abstract class FactoryMethods { public abstract Product newproduct(); } //对不同产品的实例化,由不同的工厂来具体实现,每一个工厂生产具体的商品 public class FactoryMethodA : FactoryMethods//具体工厂 { public override Product newproduct() { return new ProductA();//实现具体的实例化 } } public class FactoryMethodB : FactoryMethods//具体工厂 { public override Product newproduct() { return new ProductB();//实现具体的实例化 } } public class FactoryMethodClient { public static void GetFactoryMethod() { //产品种类是变化的,如果发生变化,新增一个工厂就可以了,在调用的地方掉用新的方法 //体现出对修改封闭,对扩展开放,新增新的功能对原来的没有影响 FactoryMethods factorysubA = new FactoryMethodA(); FactoryMethods factorysubB = new FactoryMethodB(); Product pruductA = factorysubA.newproduct(); Product pruductB = factorysubB.newproduct(); pruductA.work(); pruductB.work(); } }
抽象工厂模式实例:
/*其实工厂和抽象工厂没有多大区别,只不过是抽象工厂生产的商品是多个而已 通俗的说,就是抽象工厂模式的具体工厂里面会有多个实例具体对象的方法 更直观的就是,抽象工厂模式每个工厂一次造多个玩意,而工厂模式的每个工厂只造一个玩意*/ public abstract class Product { public abstract void work(); } public class ProductA : Product { public override void work() { Console.Write("ProductA"); } } public class ProductB : Product { public override void work() { Console.Write("ProductB"); } } public abstract class Car { public abstract void Build(); } public class CarA : Car { public override void Build() { Console.Write("Build CarA"); } } public class CarB : Car { public override void Build() { Console.Write("Build CarB"); } } public abstract class AbstractFactory { //工厂生产多个对象 public abstract Product newproduct(); public abstract Car newCar(); } public class AbstractFactoryA : AbstractFactory { public override Product newproduct() { return new ProductA();//子类里面实现具体的实例化 } public override Car newCar() { return new CarA(); } } public class AbstractFactoryB : AbstractFactory { public override Product newproduct() { return new ProductB();//子类里面实现具体的实例化 } public override Car newCar() { return new CarB(); } } public class AbstractFactoryClient { public static void GetFactoryMethod() { AbstractFactory factorysubA = new AbstractFactoryA(); AbstractFactory factorysubB = new AbstractFactoryA(); Product pruductA = factorysubA.newproduct(); Product pruductB = factorysubB.newproduct(); Car factorycarA = factorysubA.newCar(); factorycarA.Build(); pruductA.work(); pruductB.work(); } }
可以看出来,工厂模式的工厂,实例化的对象只有一个,如果实例化的对象是多个,就成了抽象工厂模式,其实工厂模式和抽象工厂也就这点区别,抽象工厂的问题是如果有创建对象变化的时候,还是要变化代码,重新生成,后面会介绍用反射解决这个问题