2.工厂方法模式

工程方法模式和简单工程合并成同一个模式,所以标题都用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();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值