C# 工厂方法模式

栏目总目录


概念

工厂方法模式是一种创建型设计模式,它定义了一个用于创建对象的接口,但让子类决定要实例化的类是哪一个。工厂方法让类的实例化推迟到子类中进行。这种模式的主要目的是将对象的创建与使用解耦,使得系统更加灵活和可扩展。

角色

  1. Product(产品角色):定义了产品的接口,是工厂方法模式所创建对象的超类型,也就是产品对象的共同父类或接口。

  2. Concrete Product(具体产品角色):实现了Product接口的具体类,被具体工厂类所创建。

  3. Creator(创建者角色):声明了工厂方法,该方法是一个返回Product类型对象的方法,但返回的Product类型对象是在子类中实现的。通常还提供一个用于创建产品对象的接口。

  4. Concrete Creator(具体创建者角色):实现了Creator接口中定义的工厂方法,返回一个Concrete Product实例。

好处

  1. 解耦:将产品的创建与使用解耦,使得系统更加灵活和可扩展。
  2. 符合开闭原则:新增产品类时,无需修改工厂类代码,只需新增具体产品类和具体工厂类即可。
  3. 提高灵活性:通过子类来决定创建哪个具体产品对象,可以在运行时动态地决定创建哪种产品对象。

应用场景

  1. 当一个类不知道它所必须创建的对象的类时。
  2. 当一个类希望由它的子类来指定它所创建的对象时。
  3. 当类将创建对象的职责委托给多个帮助子类中的某一个,并且你希望将哪一个帮助子类是代理者这一信息局部化时。

示例代码

// Product 角色
public interface IDocument
{
    void Display();
}

// Concrete Product 角色
public class TextDocument : IDocument
{
    public void Display()
    {
        Console.WriteLine("Displaying Text Document");
    }
}

public class PDFDocument : IDocument
{
    public void Display()
    {
        Console.WriteLine("Displaying PDF Document");
    }
}

// Creator 角色
public interface IDocumentFactory
{
    IDocument CreateDocument();
}

// Concrete Creator 角色
public class TextDocumentFactory : IDocumentFactory
{
    public IDocument CreateDocument()
    {
        return new TextDocument();
    }
}

public class PDFDocumentFactory : IDocumentFactory
{
    public IDocument CreateDocument()
    {
        return new PDFDocument();
    }
}

// 客户端代码
class Program
{
    static void Main(string[] args)
    {
        IDocumentFactory factory1 = new TextDocumentFactory();
        IDocument doc1 = factory1.CreateDocument();
        doc1.Display(); // 输出:Displaying Text Document

        IDocumentFactory factory2 = new PDFDocumentFactory();
        IDocument doc2 = factory2.CreateDocument();
        doc2.Display(); // 输出:Displaying PDF Document
    }
}

总结

工厂方法模式是一种非常有用的创建型设计模式,它通过定义一个创建对象的接口(即工厂接口),但将具体创建对象的任务交给子类去完成。这种模式的主要优点在于它将对象的创建与使用分离,降低了系统的耦合度,增加了系统的灵活性和可扩展性。

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

語衣

感谢大哥

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值