工厂模式(Factory Method Pattern)
模式定义
工厂方法模式(Factory Method Pattern)又称为工厂模式,也叫虚拟构造器(Virtual Constructor)模式或者多态工厂(Polymorphic Factory)模式,它属于类创建型模式。在工厂方法模式中,工厂父类负责定义创建产品对象的公共接口,而工厂子类则负责生成具体的产品对象,这样做的目的是将产品类的实例化操作延迟到工厂子类中完成,即通过工厂子类来确定究竟应该实例化哪一个具体产品类。
UML类图
- Product 抽象产品 定义产品的接口,是工厂模式所创建对象的超类型,产品对象的共同父类;
- ConcreteProduct 具体产品 继承抽象产品
- Factory 抽象工厂 定义创建产品对象的公共接口
- ConcreteFactory 具体工厂 实现工厂父类接口
代码结构组成
public class FactoryApp
{
public static void Run()
{
Creator[] creators = new Creator[2];
creators[0] = new ConcreteCreatorA();
creators[1] = new ConcreteCreatorB();
foreach(Creator creator in creators)
{
Product product = creator.FactoryMothed();
Console.WriteLine("Created {0}", product.GetType().Name);
}
}
}
public class Product
{ }
public class ConcreteProductA:Product
{ }
public class ConcreteProductB:Product
{ }
public abstract class Creator
{
public abstract Product FactoryMothed();
}
public class ConcreteCreatorA:Creator
{
public override Product FactoryMothed()
{
return new ConcreteProductA();
}
}
public class ConcreteCreatorB:Creator
{
public override Product FactoryMothed()
{
return new ConcreteProductB();
}
}
情景案例
以麦当劳的汉堡为例,假设汉堡有两种牛肉堡和鸡肉堡,不同的汉堡有不同的汉堡厨师制作。
可能有疑问:为是么是有工厂设计模式呢,反而多个多类更麻烦?
- 复用代码代码: 如果创建厨师类需要复杂的过程,比如验证厨艺水平等等,并不是简单通过new就能完成,那么将这些验证放入工厂可以在不同地方复用代码,后期只需维护一处代码
- 容易扩展: 如果再家一个芝士堡只需添加芝士堡类与芝士堡厨师类,满足开闭原则
public class FactoryApp
{
public static void Run()
{
BurgerCook[] burgerCook = new BurgerCook[2];
burgerCook[0] = new BeefBurgerCook();
burgerCook[1] = new ChickenBurgerCook();
foreach (BurgerCook cook in burgerCook)
{
Burger burger = cook.MarkBurger();
Console.WriteLine("Created {0}", burger.GetType().Name);
}
}
}
public class Burger
{ }
public class BeefBurger : Burger
{ }
public class ChickenBurger : Burger
{ }
public abstract class BurgerCook
{
public abstract Burger MarkBurger();
}
public class BeefBurgerCook : BurgerCook
{
public override Burger MarkBurger()
{
return new BeefBurger();
}
}
public class ChickenBurgerCook : BurgerCook
{
public override Burger MarkBurger()
{
return new ChickenBurger();
}
}