首页 > 编程语言 >C#设计模式详解:从简单工厂到抽象工厂

C#设计模式详解:从简单工厂到抽象工厂

时间:2024-10-12 08:51:01浏览次数:3  
标签:C# void public IFactory 工厂 new 设计模式 class

在C#中,简单工厂(Simple Factory)和抽象工厂(Abstract Factory)是两种常用的设计模式,它们都属于创建型设计模式,用于创建对象而无需在代码中显式指定具体的类。尽管它们的目的相似,但在复杂性和灵活性方面存在显著差异。

简单工厂(Simple Factory)

简单工厂模式是一种不属于GoF(四人帮)23种设计模式之一的模式,但它非常流行且广泛使用。它定义了一个创建对象的接口,但让子类决定要实例化的类是哪一个。工厂类使用静态方法来创建对象,客户端可以通过调用这些静态方法来获取所需的实例,而无需指定具体的类。

优点

  • 客户端不需要知道如何创建具体产品的类。
  • 减少了代码中的对象创建逻辑,简化了客户端代码。

缺点

  • 如果系统中需要增加新的产品类,则需要修改工厂类,违反了开闭原则(对扩展开放,对修改关闭)。
  • 工厂类负责所有产品的创建,这可能会导致工厂类变得非常庞大。

示例代码

interface Product
{
    void Use();
}

class ConcreteProductA : Product
{
    public void Use()
    {
        Console.WriteLine("Using ConcreteProductA");
    }
}

class ConcreteProductB : Product
{
    public void Use()
    {
        Console.WriteLine("Using ConcreteProductB");
    }
}

class SimpleFactory
{
    public static Product CreateProduct(string type)
    {
        switch (type)
        {
            case "A":
                return new ConcreteProductA();
            case "B":
                return new ConcreteProductB();
            default:
                throw new ArgumentException("Unknown product type");
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Product productA = SimpleFactory.CreateProduct("A");
        productA.Use();

        Product productB = SimpleFactory.CreateProduct("B");
        productB.Use();
    }
}

抽象工厂(Abstract Factory)

抽象工厂模式提供了一种创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。客户端不依赖于产品的具体实现,而是依赖于抽象工厂和抽象产品。这允许客户端在不需要修改代码的情况下,就可以更换产品的具体实现。

优点

  • 可以在类的内部使用产品族中的产品,而不需要知道具体的实现。
  • 增加了系统的灵活性和可扩展性。

缺点

  • 如果产品族中的产品数量过多,会导致工厂接口过于庞大,难以维护。
  • 系统扩展复杂,如果需要添加新的产品族,就需要修改抽象工厂类及其所有子类。

示例代码(假设有两个产品族:GUI和CLI):

interface IButton
{
    void Paint();
}

interface IText
{
    void Write();
}

class GuiButton : IButton
{
    public void Paint()
    {
        Console.WriteLine("GUI Button painted");
    }
}

class GuiText : IText
{
    public void Write()
    {
        Console.WriteLine("GUI Text written");
    }
}

class CliButton : IButton
{
    public void Paint()
    {
        Console.WriteLine("CLI Button painted");
    }
}

class CliText : IText
{
    public void Write()
    {
        Console.WriteLine("CLI Text written");
    }
}

interface IFactory
{
    IButton CreateButton();
    IText CreateText();
}

class GuiFactory : IFactory
{
    public IButton CreateButton()
    {
        return new GuiButton();
    }

    public IText CreateText()
    {
        return new GuiText();
    }
}

class CliFactory : IFactory
{
    public IButton CreateButton()
    {
        return new CliButton();
    }

    public IText CreateText()
    {
        return new CliText();
    }
}

class Program
{
    static void Main(string[] args)
    {
        IFactory guiFactory = new GuiFactory();
        guiFactory.CreateButton().Paint();
        guiFactory.CreateText().Write();

        IFactory cliFactory = new CliFactory();
        cliFactory.CreateButton().Paint();
        cliFactory.CreateText().Write();
    }
}

在这个例子中,IFactory 是一个抽象工厂接口,定义了创建按钮和文本对象的方法。GuiFactoryCliFactory 是具体的工厂类,分别实现了 IFactory 接口,并返回特定于GUI和CLI的产品对象。

标签:C#,void,public,IFactory,工厂,new,设计模式,class
From: https://blog.csdn.net/x1234w4321/article/details/142250315

相关文章

  • 2023 Benelux Algorithm Programming Contest (BAPC 23)
    A-\texttt题意\(n\)个软件包,已知大小,可以同时下载\(k\)个,已经下载好了\(m\)个,选\(k\)个下载使得下载完后进度最大,输出已完成进度所占百分比。思路选最大的\(m+k\)个。代码点击查看代码#include<bits/stdc++.h>usingnamespacestd;#defineintlonglongvoid......
  • R语言使用randomForest包中的randomForest函数构建随机森林模型、使用importance函数
    R语言使用randomForest包中的randomForest函数构建随机森林模型、使用importance函数查看特征重要度、使用table函数计算混淆矩阵评估分类模型性能、包外错误估计OOB(out-of-bagerrorestimate)目录R语言使用randomForest包中的randomForest函数构建随机森林模型(Randomfores......
  • electron-vite_4使用WebContentsView快速集成已有项目
    Web嵌入官方推荐使用WebContentsView;集成也比较简单,但还是需要你单独写点东西;src/main/index.ts进行修改import{app,shell,BrowserWindow,ipcMain,nativeImage,WebContentsView,dialog}from'electron';functioncreateWindow():void{//1.创建br......
  • electron-vite_6js-cookie失效
    我们项目是用了js-cookie,后续集成的时候发现,无法进入首页;经过排查是js-cookie无法使用,可能是electron打包后的项目运行的时候是file:///猜测原因:因为Cookie是与域名相关联的,而file:///协议没有域名,因此Cookie可能无法正常工作。file:///C:/Users/Administrator/AppData/......
  • 【AN】Adobe Animate多媒体创作和电脑动画程序win/mac下载安装
    目录AdobeAN软件功能AdobeAN软件下载与安装下载:安装:AdobeAN软件功能AdobeAN软件,全称AdobeAnimate,是一款由AdobeSystems开发的功能强大的多媒体创作和电脑动画程序。以下是其主要功能概述:动画制作:2D及简单3D动画:AdobeAnimate能够轻松创建高质量的2D动画,并支持......
  • 微软发布Windows 11 2024更新,新型Copilot+ AI PC功能亮相
    前言微软在Windows11的2024更新中加强了对人工智能的应用,推出了新功能Copilot+。此次更新的版本号为26100.1742,Copilot+将首先在WindowsInsider中推出,计划于11月向特定设备和市场推广,用户需开启“尽快获取最新更新”选项以接收此更新。系统获取https://pan.xunlei.com......
  • LeetCode题练习与总结:单词规律--290
    一、题目描述给定一种规律 pattern 和一个字符串 s ,判断 s 是否遵循相同的规律。这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 s 中的每个非空单词之间存在着双向连接的对应规律。示例1:输入:pattern="abba",s="dogcatcatdog"输出:tr......
  • const与一级指针
    const与一级指针在C/C++中,const关键字用于表示一个变量的值是不可改变的。通常,它修饰离它最近的类型,意思是它所修饰的部分不能被修改。根据它在声明中的位置,const可以修饰指针或者指针所指向的值。1.const修饰变量如果const修饰变量,则该变量是常量,不能被修改。con......
  • 《综合与Design Compiler》笔记
    《综合与DesignCompiler》笔记一直没系统的整理过DC这块的东西,这里借助一个挺好的文档《综合与DeisgnCompiler》以及我自己的经验和理解来归总一下。1.综合是什么综合是使用软件的方法来设计硬件,然后将门级电路实现与优化的工作留给综合工具的一种设计方法。它是根据一个系......
  • C# unsafe 快速复制数组
    ///<summary>///复制内存///</summary>///<paramname="dest">目标指针位置</param>///<paramname="src">源指针位置</param>///<paramname="count">字节长度</param>......