C#常见的设计模式-创建型模式

引言

在软件开发过程中,设计模式是一种被广泛采用的思想和实践,可以提供一种标准化的解决方案,以解决特定问题。设计模式分为三种类型:创建型模式、结构型模式和行为型模式。本篇文章将重点介绍C#中常见的创建型模式。
在这里插入图片描述


目录

    • 引言
    • 创建型模式的作用
    • 常见的创建型模式
      • 1. 简单工厂模式 (Simple Factory Pattern)
      • 2. 工厂方法模式 (Factory Method Pattern)
      • 3. 抽象工厂模式 (Abstract Factory Pattern)
      • 4. 单例模式 (Singleton Pattern)
      • 5. 原型模式 (Prototype Pattern)
      • 6. 建造者模式 (Builder Pattern)
    • 总结


创建型模式的作用

创建型模式主要关注对象的创建过程,并提供一种机制来创建对象,以使代码更加灵活、可维护和可扩展。创建型模式可以帮助我们降低系统的耦合度,使系统更具弹性,并且促进面向对象的设计原则的实施。

在这里插入图片描述


常见的创建型模式

1. 简单工厂模式 (Simple Factory Pattern)

简单工厂模式通过一个类来封装对象的创建过程,根据不同的条件返回不同的对象。在C#中,我们可以通过使用静态方法或者工厂类来实现简单工厂模式。

public class SimpleFactory
{
    public static IProduct CreateProduct(string type)
    {
        switch (type)
        {
            case "A":
                return new ProductA();
            case "B":
                return new ProductB();
            default:
                throw new ArgumentException("Invalid type");
        }
    }
}

public interface IProduct
{
    void DoSomething();
}

public class ProductA : IProduct
{
    public void DoSomething()
    {
        Console.WriteLine("ProductA does something.");
    }
}

public class ProductB : IProduct
{
    public void DoSomething()
    {
        Console.WriteLine("ProductB does something.");
    }
}

public class Client
{
    public void Main()
    {
        IProduct product = SimpleFactory.CreateProduct("A");
        product.DoSomething();
    }
}

2. 工厂方法模式 (Factory Method Pattern)

工厂方法模式将对象的创建延迟到子类中进行,每个子类都负责创建自己的对象。这样可以通过使用多态性来实现在运行时动态地选择合适的对象。

public interface IProductFactory
{
    IProduct CreateProduct();
}

public interface IProduct
{
    void DoSomething();
}

public class ProductAFactory : IProductFactory
{
    public IProduct CreateProduct()
    {
        return new ProductA();
    }
}

public class ProductBFactory : IProductFactory
{
    public IProduct CreateProduct()
    {
        return new ProductB();
    }
}

public class ProductA : IProduct
{
    public void DoSomething()
    {
        Console.WriteLine("ProductA does something.");
    }
}

public class ProductB : IProduct
{
    public void DoSomething()
    {
        Console.WriteLine("ProductB does something.");
    }
}

public class Client
{
    public void Main(IProductFactory factory)
    {
        IProduct product = factory.CreateProduct();
        product.DoSomething();
    }
}

3. 抽象工厂模式 (Abstract Factory Pattern)

抽象工厂模式提供了一个接口来创建一系列相互依赖或者有关联的对象,而不用指定他们具体的类。在C#中,我们可以通过使用抽象类或者接口来实现抽象工厂模式。

public interface IAbstractFactory
{
    IProductA CreateProductA();
    IProductB CreateProductB();
}

public interface IProductA
{
    void DoSomething();
}

public interface IProductB
{
    void DoSomething();
}

public class ConcreteFactory1 : IAbstractFactory
{
    public IProductA CreateProductA()
    {
        return new ProductA1();
    }

    public IProductB CreateProductB()
    {
        return new ProductB1();
    }
}

public class ConcreteFactory2 : IAbstractFactory
{
    public IProductA CreateProductA()
    {
        return new ProductA2();
    }

    public IProductB CreateProductB()
    {
        return new ProductB2();
    }
}

public class ProductA1 : IProductA
{
    public void DoSomething()
    {
        Console.WriteLine("ProductA1 does something.");
    }
}

public class ProductB1 : IProductB
{
    public void DoSomething()
    {
        Console.WriteLine("ProductB1 does something.");
    }
}

public class ProductA2 : IProductA
{
    public void DoSomething()
    {
        Console.WriteLine("ProductA2 does something.");
    }
}

public class ProductB2 : IProductB
{
    public void DoSomething()
    {
        Console.WriteLine("ProductB2 does something.");
    }
}

public class Client
{
    public void Main(IAbstractFactory factory)
    {
        IProductA productA = factory.CreateProductA();
        IProductB productB = factory.CreateProductB();
        
        productA.DoSomething();
        productB.DoSomething();
    }
}

4. 单例模式 (Singleton Pattern)

单例模式保证一个类只有一个实例,并提供一个全局访问点来访问该实例。在C#中,可以通过使用静态变量或者静态属性来实现单例模式。

public sealed class Singleton
{
    private static Singleton instance;
    private static readonly object lockObject = new object();

    private Singleton() { }

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                lock (lockObject)
                {
                    if (instance == null)
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
}

public class Client
{
    public void Main()
    {
        Singleton singleton = Singleton.Instance;
    }
}

5. 原型模式 (Prototype Pattern)

原型模式使用原型来创建对象,通过复制现有的对象来创建新的对象。在C#中,可以通过实现ICloneable接口来实现原型模式。

public abstract class Prototype : ICloneable
{
    public abstract object Clone();
}

public class ConcretePrototypeA : Prototype
{
    public override object Clone()
    {
        return (ConcretePrototypeA)this.MemberwiseClone();
    }
}

public class ConcretePrototypeB : Prototype
{
    public override object Clone()
    {
        return (ConcretePrototypeB)this.MemberwiseClone();
    }
}

public class Client
{
    public void Main()
    {
        Prototype prototypeA = new ConcretePrototypeA();
        Prototype prototypeB = new ConcretePrototypeB();

        Prototype cloneA = (Prototype)prototypeA.Clone();
        Prototype cloneB = (Prototype)prototypeB.Clone();
    }
}

6. 建造者模式 (Builder Pattern)

建造者模式将一个复杂对象的构建过程与其表示分离,使得同样的构建过程可以创建不同的表示。在C#中,可以通过使用链式调用或者指导者来实现建造者模式。

public class Product
{
    private string part1;
    private string part2;
    private string part3;

    public string Part1 { get { return part1; } }
    public string Part2 { get { return part2; } }
    public string Part3 { get { return part3; } }

    public Product(string part1, string part2, string part3)
    {
        this.part1 = part1;
        this.part2 = part2;
        this.part3 = part3;
    }
}

public interface IBuilder
{
    void BuildPart1(string value);
    void BuildPart2(string value);
    void BuildPart3(string value);
    Product GetResult();
}

public class ConcreteBuilder : IBuilder
{
    private string part1;
    private string part2;
    private string part3;

    public void BuildPart1(string value)
    {
        part1 = value;
    }

    public void BuildPart2(string value)
    {
        part2 = value;
    }

    public void BuildPart3(string value)
    {
        part3 = value;
    }

    public Product GetResult()
    {
        return new Product(part1, part2, part3);
    }
}

public class Director
{
    public Product Construct(IBuilder builder)
    {
        builder.BuildPart1("Part1");
        builder.BuildPart2("Part2");
        builder.BuildPart3("Part3");

        return builder.GetResult();
    }
}

public class Client
{
    public void Main()
    {
        IBuilder builder = new ConcreteBuilder();
        Director director = new Director();

        Product product = director.Construct(builder);
    }
}

在这里插入图片描述

总结

创建型模式是软件设计中的重要概念,可以帮助我们更好地组织和管理对象的创建过程。本篇文章介绍了C#中常见的创建型模式,包括简单工厂模式、工厂方法模式、抽象工厂模式、单例模式、原型模式和建造者模式。通过熟悉和灵活应用这些模式,我们可以写出更加可维护、可扩展和可测试的代码。

参考文献:

  • Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/205312.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【23种设计模式·全精解析 | 行为型模式篇】11种行为型模式的结构概述、案例实现、优缺点、扩展对比、使用场景、源码解析

文章目录 行为型模式1、模板方法模式(1)概述(2)结构(3)案例实现(4)优缺点(5)适用场景(6)JDK源码解析(7)模板方…

1-3、DOSBox环境搭建

语雀原文链接 文章目录 1、安装DOSBox2、Debug进入Debugrdeautq 1、安装DOSBox 官网下载下载地址:https://www.dosbox.com/download.php?main1此处直接下载这个附件(内部有8086的DEBUG.EXE环境)8086汇编工作环境.rar执行安装DOSBox0.74-wi…

pandas-profiling / ydata-profiling介绍与使用教程

文章目录 pandas-profilingydata-profilingydata-profiling实际应用iris鸢尾花数据集分析 pandas-profiling pandas_profiling 官网(https://pypi.org/project/pandas-profiling/)大概在23年4月前发出如下公告: Deprecated pandas-profilin…

keepalive路由缓存实现前进刷新后退缓存

1.在app.vue中配置全局的keepalive并用includes指定要缓存的组件路由name名字数组 <keep-alive :include"keepCachedViews"><router-view /></keep-alive>computed: {keepCachedViews() {console.log(this.$store.getters.keepCachedViews, this.…

提升技能素养,AMCAP做出合适的决策

近年来&#xff0c;智能配置投资与理财逐渐受到关注并走俏。这是一种简单快捷的智慧化理财方式&#xff0c;通过将个人和家族的闲置资金投入到低风险高流动性的产品中。 国际财富管理投资机构AMCAP集团金融分析师表示&#xff1a;智能配置投资与理财之所以持续走俏&#xff0c…

Redis String类型

String 类型是 Redis 最基本的数据类型&#xff0c;String 类型在 Redis 内部使用动态长度数组实现&#xff0c;Redis 在存储数据时会根据数据的大小动态地调整数组的长度。Redis 中字符串类型的值最大可以达到 512 MB。 关于字符串需要特别注意∶ 首先&#xff0c;Redis 中所…

Linux下查看目录大小

查看目录大小 Linux下查看当前目录大小&#xff0c;可用一下命令&#xff1a; du -h --max-depth1它会从下到大的显示文件的大小。

FastDFS+Nginx - 本地搭建文件服务器同时实现在外远程访问「内网穿透」

文章目录 前言1. 本地搭建FastDFS文件系统1.1 环境安装1.2 安装libfastcommon1.3 安装FastDFS1.4 配置Tracker1.5 配置Storage1.6 测试上传下载1.7 与Nginx整合1.8 安装Nginx1.9 配置Nginx 2. 局域网测试访问FastDFS3. 安装cpolar内网穿透4. 配置公网访问地址5. 固定公网地址5.…

【MySQL】视图:简化查询

文章目录 create view … as创建视图更改或删除视图drop view 删除视图replace关键字&#xff1a;更改视图 可更新视图with check option子句&#xff1a;防止行被删除视图的其他优点简化查询减小数据库设计改动的影响使用视图限制基础表访问 create view … as创建视图 把常用…

Python 异常处理(try except)

文章目录 1 概述1.1 异常示例 2 异常处理2.1 捕获异常 try except2.2 抛出异常 raise 3 异常类型3.1 内置异常3.2 自定义异常 1 概述 1.1 异常示例 异常&#xff1a;程序执行中出现错误&#xff0c;若不处理&#xff0c;则程序终止 示例代码&#xff1a; v 6 / 0 # 除数不…

GPT带我学Openpyxl操作Excel

注&#xff1a;以下文字大部分文字和代码由GPT生成 一、openpyxl详细介绍 Openpyxl是一个用于读取和编写Excel 2010 xlsx/xlsm/xltx/xltm文件的Python库。它允许您使用Python操作Excel文件&#xff0c;包括创建新的工作簿、读取和修改现有工作簿中的数据、设置单元格格式以及编…

信贷专员简历模板

这份简历内容&#xff0c;以信贷专员招聘需求为背景&#xff0c;我们制作了1份全面、专业且具有参考价值的简历案例&#xff0c;大家可以灵活借鉴。 信贷专员简历在线编辑下载&#xff1a;百度幻主简历 求职意向 求职类型&#xff1a;全职 意向岗位&#xff1a;信贷专员 …

2002-2021年全国各省产业结构合理化高级化指数数据(含原始数据+计算过程+计算结果)

2002-2021年全国各省产业结构合理化高级化指数数据&#xff08;含原始数据计算过程计算结果&#xff09; 1、时间&#xff1a;2002-2021年 2、指标&#xff1a;地区、时间、就业总人数&#xff08;万人&#xff09;、第一产业就业人数&#xff08;万人&#xff09;、第二产业…

C++ ini配置文件的简单读取使用

ini文件就是简单的section 下面有对应的键值对 std::map<std::string, std::map<std::string, std::string>>MyIni::readIniFile() {std::ifstream file(filename);if (!file.is_open()) {std::cerr << "Error: Unable to open file " << …

代码随想录算法训练营第一天 | 704. 二分查找 27. 移除元素

class Solution { public:int search(vector<int>& nums, int target) {int l0;int rnums.size()-1;while(l<r){int mid(lr)>>1;if(targetnums[mid]) return mid;if(target>nums[mid]){lmid1;}else{rmid-1;}}return -1;} }; 之前就已经熟悉二分法了&am…

禁奥义·SQL秘籍

sql secret scripts sql 语法顺序、执行顺序、执行过程、要点解析、优化技巧。 1、语法顺序 如上图所示&#xff0c;为 sql 语法顺序与执行顺序对照图。其具体含义如下&#xff1a; 0、select&#xff1a; 用于从数据库中选取数据&#xff0c;即表示从数据库中查询到的数据的…

中兴亮相中国国际现代化铁路技术装备展览会 筑智铁路5G同行

近日&#xff0c;第十六届中国国际现代化铁路技术装备展览会在北京中国国际展览中心举办&#xff0c;中兴以“数智铁路&#xff0c;5G同行”主题亮相本次展览会&#xff0c;并全面展示了“数字铁路网络基础设施”、“云边结合的铁路行业云”、“数字铁路赋能赋智”等方面的最新…

VMware Workstation 无法连接到虚拟机问题排查(一)

文章目录 VMware Workstation无法连接到虚拟机问题排查1. 问题概述2. 排查思路3. 问题修改4. 总结 VMware Workstation无法连接到虚拟机问题排查 近期在使用新电脑安装VMware Workstation&#xff0c;启动虚拟机实例的时候出现失败&#xff0c;提示为:“VMware Workstation 无…

全网最新最全的Jmeter接口测试:jmeter_定时器

固定定时器 如果你需要让每个线程在请求之前按相同的指定时间停顿&#xff0c;那么可以使用这个定时器&#xff1b;需要注意的是&#xff0c;固定定时器的延时不会计入单个sampler的响应时间&#xff0c;但会计入事务控制器的时间 1、使用固定定时器位置在http请求中&#xf…

sublime Text使用

1、增加install 命令面板 工具(tool)->控制面板(command palette) -> 输入install ->安装第一个install package controller&#xff0c;以下安装过了&#xff0c;所以没展示 2、安装json格式化工具 点击install package&#xff0c;等几秒会进入控制面板&#xff0…