工厂方法模式:解决简单工厂模式中系统难以扩展的问题而设计
实现方法:把具体的产品创建推迟到子类中,此时工厂类就不在负责所有产品的创建,而只是给出具体工厂必须实现的接口,这样工厂方法模式就可以允许系统不修改工厂类逻辑的情况下添加新产品,这样也就克服了简单工厂模式中缺点。
//客户端调用
private void btnFactoryPatten_Click(object sender, EventArgs e)
{
//初始化做菜的两个工厂()
Creater shreddedPorkWithPotatoesFactory = new ShreddedPorkWithPotatoesFactory();
Creater tomatoScrambledEggsFactory = new TomatoScrambledEggsFactory();
//开始做西红柿炒蛋
Food tomatoScrambledEggs = tomatoScrambledEggsFactory.CreateFoodFactory();
tomatoScrambledEggs.Print();
//开始做土豆肉丝
Food shreddedPorkWithPotatoes = shreddedPorkWithPotatoesFactory.CreateFoodFactory();
shreddedPorkWithPotatoes.Print();
//添加新的功能 想添加点肉末芥子 需要另外初始化一个肉末芥子
Creater minceMeatEggplantFactor = new MincedMeatEggplantFactory();
//利用肉末芥子工厂来创建肉末芥子这道菜
Food minceMeatEggplant = minceMeatEggplantFactor.CreateFoodFactory();
minceMeatEggplant.Print();
}
}
/// <summary>
/// 肉末芥子这道菜
/// </summary>
public class MincedMeatEggplant : Food
{
/// <summary>
/// 重写抽象类中的方法
/// </summary>
public override void Print()
{
MessageBox.Show("肉末茄子好了");
}
}
/// <summary>
/// 肉末芥子工厂类,负责创建肉末芥子这道菜
/// </summary>
public class MincedMeatEggplantFactory : Creater
{
/// <summary>
/// 负责创建肉末茄子这道菜
/// </summary>
/// <returns></returns>
public override Food CreateFoodFactory()
{
return new MincedMeatEggplant();
}
}
/// <summary>
/// 抽象工程类
/// </summary>
public abstract class Creater
{
//工厂方法
public abstract Food CreateFoodFactory();
}
public class TomatoScrambledEggsFactory : Creater
{
/// <summary>
/// 负责创建西红柿炒蛋这道菜
/// </summary>
/// <returns></returns>
public override Food CreateFoodFactory()
{
return new TomatoScrambledEggs();
}
}
public class ShreddedPorkWithPotatoesFactory : Creater
{
/// <summary>
/// 负责创建土豆肉丝这道菜
/// </summary>
/// <returns></returns>
public override Food CreateFoodFactory()
{
return new ShreddedPorkWithPotatoes();
}
}