工程方法模式和简单工程合并成同一个模式,所以标题都用2了。。。不要在意这些细节
介绍
简单工厂模式的缺点很明显,简单工厂模式系统难以扩展,一旦添加新产品就不得不修改简单工厂方法,这样就会造成简单工厂的实现逻辑过于复杂,工厂方法模式可以解决简单工厂模式中存在的这个问题。
核心要点
“一个工场只能生产单个东西。”
工厂接口,实现不同的工厂
把具体产品的创建推迟到子类中,此时工厂类不再负责所有产品的创建,而只是给出具体工厂必须实现的接口,这样工厂方法模式就可以允许系统不修改工厂类逻辑的情况下来添加新产品
例子
class UIElement
{
public string Name
{
get;
set;
}
}
interface ILegendFactory
{
UIElement Create();
}
class LegendFactory:ILegendFactory
{
public UIElement Create()
{
return new UIElement() { Name = "Legend" };
}
}
class TitleFactory:ILegendFactory
{
public UIElement Create()
{
return new UIElement() { Name = "Title" };
}
}
class SymbolFactory:ILegendFactory
{
public UIElement Create()
{
return new UIElement() { Name="Smybol"};
}
}
//使用
class Program
{
static void Main(string[] args)
{
ILegendFactory factory = new SymbolFactory();
Console.WriteLine( factory.Create().Name);
Console.ReadKey();
}
}