首页 > 编程语言 >C# 常用设计模式有哪些

C# 常用设计模式有哪些

时间:2023-05-23 13:02:52浏览次数:40  
标签:哪些 C# void component public new Operation 设计模式 class

原文地址:C# 常用设计模式有哪些 - C#入门教程 - .NET果糖网 (donet5.com)

C#中常用的设计模式有很多,以下列举几个常用的:

1.工厂模式(Factory Pattern)

通过工厂方法创建对象,隐藏对象的实例化过程,提供灵活性和可扩展性。

 1 public interface IAnimal
 2 {
 3     void Speak();
 4 }
 5  
 6 public class Cat : IAnimal
 7 {
 8     public void Speak()
 9     {
10         Console.WriteLine("Meow");
11     }
12 }
13  
14 public class Dog : IAnimal
15 {
16     public void Speak()
17     {
18         Console.WriteLine("Woof");
19     }
20 }
21  
22 public class AnimalFactory
23 {
24     public IAnimal CreateAnimal(string animalType)
25     {
26         switch (animalType.ToLower())
27         {
28             case "cat":
29                 return new Cat();
30             case "dog":
31                 return new Dog();
32             default:
33                 throw new ArgumentException($"Invalid animal type: {animalType}");
34         }
35     }
36 }
37  
38 // Usage
39 AnimalFactory animalFactory = new AnimalFactory();
40 IAnimal animal1 = animalFactory.CreateAnimal("cat");
41 IAnimal animal2 = animalFactory.CreateAnimal("dog");
42 animal1.Speak(); // Output: Meow
43 animal2.Speak(); // Output: Woof

2.单例模式(Singleton Pattern)

保证一个类只有一个实例,并提供一个全局访问点。

 1 public sealed class Singleton
 2 {
 3     private static readonly Singleton instance = new Singleton();
 4  
 5     private Singleton() { }
 6  
 7     public static Singleton Instance
 8     {
 9         get
10         {
11             return instance;
12         }
13     }
14  
15     public void DoSomething()
16     {
17         Console.WriteLine("Singleton instance is doing something");
18     }
19 }
20  
21 // Usage
22 Singleton singleton1 = Singleton.Instance;
23 Singleton singleton2 = Singleton.Instance;
24 Console.WriteLine(singleton1 == singleton2); // Output: True
25 singleton1.DoSomething(); // Output: Singleton instance is doing something

3.装饰器模式(Decorator Pattern)

动态地给一个对象添加一些额外的职责,而不影响其他对象。

 1 public interface IComponent
 2 {
 3     void Operation();
 4 }
 5  
 6 public class ConcreteComponent : IComponent
 7 {
 8     public void Operation()
 9     {
10         Console.WriteLine("ConcreteComponent.Operation()");
11     }
12 }
13  
14 public abstract class Decorator : IComponent
15 {
16     private IComponent component;
17  
18     public Decorator(IComponent component)
19     {
20         this.component = component;
21     }
22  
23     public virtual void Operation()
24     {
25         component.Operation();
26     }
27 }
28  
29 public class ConcreteDecoratorA : Decorator
30 {
31     public ConcreteDecoratorA(IComponent component) : base(component)
32     {
33     }
34  
35     public override void Operation()
36     {
37         base.Operation();
38         Console.WriteLine("ConcreteDecoratorA.Operation()");
39     }
40 }
41  
42 public class ConcreteDecoratorB : Decorator
43 {
44     public ConcreteDecoratorB(IComponent component) : base(component)
45     {
46     }
47  
48     public override void Operation()
49     {
50         base.Operation();
51         Console.WriteLine("ConcreteDecoratorB.Operation()");
52     }
53 }
54  
55 // Usage
56 IComponent component = new ConcreteComponent();
57 component = new ConcreteDecoratorA(component);
58 component = new ConcreteDecoratorB(component);
59 component.Operation();
60 // Output:
61 // ConcreteComponent.Operation()
62 // ConcreteDecoratorA.Operation()
63 // ConcreteDecoratorB.Operation()

4.观察者模式(Observer Pattern)

定义了一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并自动更新。

 1 // 主题对象
 2 public class Subject 
 3 {
 4     public event EventHandler StateChanged;
 5  
 6     private int state;
 7  
 8     public int State 
 9     {
10         get { return state; }
11         set 
12         {
13             state = value;
14             StateChanged?.Invoke(this, EventArgs.Empty);
15         }
16     }
17 }
18  
19 // 观察者对象
20 public class Observer 
21 {
22     private readonly Subject subject;
23  
24     public Observer(Subject subject) 
25     {
26         this.subject = subject;
27         subject.StateChanged += HandleStateChanged;
28     }
29  
30     public void HandleStateChanged(object sender, EventArgs e) 
31     {
32         Console.WriteLine("State changed to {0}", subject.State);
33     }
34 }
35  
36 // 使用观察者模式
37 var subject = new Subject();
38 var observer1 = new Observer(subject);
39 var observer2 = new Observer(subject);
40  
41 subject.State = 1; // 输出:State changed to 1
42 subject.State = 2; // 输出:State changed to 2

 

5.策略模式(Strategy Pattern)

定义了算法族,分别封装起来,让它们之间可以互相替换,使得算法的变化独立于使用它的客户端。

 1 // 策略接口
 2 public interface IPricingStrategy
 3 {
 4     decimal CalculatePrice(decimal price);
 5 }
 6  
 7 // 策略实现类
 8 public class RegularPricingStrategy : IPricingStrategy
 9 {
10     public decimal CalculatePrice(decimal price)
11     {
12         return price;
13     }
14 }
15  
16 public class DiscountPricingStrategy : IPricingStrategy
17 {
18     private decimal discountRate;
19  
20     public DiscountPricingStrategy(decimal discountRate)
21     {
22         this.discountRate = discountRate;
23     }
24  
25     public decimal CalculatePrice(decimal price)
26     {
27         return price * (1 - discountRate);
28     }
29 }
30  
31 // 上下文类
32 public class Product
33 {
34     private IPricingStrategy pricingStrategy;
35  
36     public Product(IPricingStrategy pricingStrategy)
37     {
38         this.pricingStrategy = pricingStrategy;
39     }
40  
41     public void SetPricingStrategy(IPricingStrategy pricingStrategy)
42     {
43         this.pricingStrategy = pricingStrategy;
44     }
45  
46     public decimal GetPrice(decimal price)
47     {
48         return pricingStrategy.CalculatePrice(price);
49     }
50 }

 


在这个示例中,IPricingStrategy 接口定义了策略类应实现的方法,而 RegularPricingStrategy 和 DiscountPricingStrategy 是实现策略接口的具体类。Product 类是一个上下文类,其中包含了一个 IPricingStrategy 对象,并且可以在运行时动态更改策略。这使得客户端可以使用 Product 类来计算不同价格的产品,而不必知道实际的算法或逻辑。

6.模板方法模式(Template Method Pattern)

定义了一个算法的骨架,将一些步骤延迟到子类中实现,使得子类可以改变算法的某些特定步骤。

 1 public abstract class AbstractClass
 2 {
 3     public void TemplateMethod()
 4     {
 5         Operation1();
 6         Operation2();
 7         Operation3();
 8     }
 9  
10     protected abstract void Operation1();
11     protected abstract void Operation2();
12     protected abstract void Operation3();
13 }
14  
15 public class ConcreteClass : AbstractClass
16 {
17     protected override void Operation1()
18     {
19         Console.WriteLine("ConcreteClass.Operation1");
20     }
21  
22     protected override void Operation2()
23     {
24         Console.WriteLine("ConcreteClass.Operation2");
25     }
26  
27     protected override void Operation3()
28     {
29         Console.WriteLine("ConcreteClass.Operation3");
30     }
31 }

 


7.适配器模式(Adapter Pattern)

将一个类的接口转换成客户端所期望的另一个接口,使得原本不兼容的类可以一起工作。

 1 // 目标接口
 2 public interface ITarget
 3 {
 4     void Request();
 5 }
 6  
 7 // 源接口
 8 public class Adaptee
 9 {
10     public void SpecificRequest()
11     {
12         Console.WriteLine("Adaptee.SpecificRequest");
13     }
14 }
15  
16 // 适配器
17 public class Adapter : ITarget
18 {
19     private readonly Adaptee _adaptee;
20  
21     public Adapter(Adaptee adaptee)
22     {
23         _adaptee = adaptee;
24     }
25  
26     public void Request()
27     {
28         _adaptee.SpecificRequest();
29     }
30 }
31  
32 // 客户端
33 public class Client
34 {
35     public static void Main()
36     {
37         Adaptee adaptee = new Adaptee();
38         ITarget target = new Adapter(adaptee);
39         target.Request();
40     }
41 }

在这个示例中,ITarget 是目标接口,Adaptee 是源接口,Adapter 是适配器。通过适配器,ITarget 接口中的 Request() 方法可以调用 Adaptee 类中的 SpecificRequest() 方法。在客户端中,可以创建一个 Adaptee 对象,然后使用它来创建一个适配器,最后调用适配器的 Request() 方法,以调用 Adaptee 中的 SpecificRequest() 方法。

9.命令模式(Command Pattern)

将一个请求封装为一个对象,从而可以用不同的请求对客户端进行参数化,使得请求的排队或记录日志等操作成为可能。

 1 // 定义命令接口
 2 public interface ICommand
 3 {
 4     void Execute();
 5 }
 6  
 7 // 定义具体命令类
 8 public class ConcreteCommand : ICommand
 9 {
10     private readonly Receiver _receiver;
11     private readonly string _parameter;
12  
13     public ConcreteCommand(Receiver receiver, string parameter)
14     {
15         _receiver = receiver;
16         _parameter = parameter;
17     }
18  
19     public void Execute()
20     {
21         _receiver.Action(_parameter);
22     }
23 }
24  
25 // 定义命令调用者类
26 public class Invoker
27 {
28     private ICommand _command;
29  
30     public void SetCommand(ICommand command)
31     {
32         _command = command;
33     }
34  
35     public void ExecuteCommand()
36     {
37         _command.Execute();
38     }
39 }
40  
41 // 定义接收者类
42 public class Receiver
43 {
44     public void Action(string parameter)
45     {
46         Console.WriteLine("Receiver is doing action with parameter: {0}", parameter);
47     }
48 }
49  
50 // 客户端代码
51 class Client
52 {
53     static void Main(string[] args)
54     {
55         // 创建接收者对象
56         Receiver receiver = new Receiver();
57  
58         // 创建具体命令对象,并传入接收者对象和参数
59         ConcreteCommand command = new ConcreteCommand(receiver, "test");
60  
61         // 创建命令调用者对象,并将命令对象传递给它
62         Invoker invoker = new Invoker();
63         invoker.SetCommand(command);
64  
65         // 执行命令
66         invoker.ExecuteCommand();
67     }
68 }

 

这些设计模式可以使程序更加灵活、易于维护和扩展,并且在实际的开发中被广泛应用。

 

标签:哪些,C#,void,component,public,new,Operation,设计模式,class
From: https://www.cnblogs.com/Andy-Blog/p/17424232.html

相关文章

  • 7千多最好的古诗欣赏词库ACCESS数据库
    古诗词类的数据虽然已经搞了很多,但是各有各的特点,今天再发一款适合于开发人员开发产品的古诗词库,如果有技术,那么这个诗词类的数据库就是诗词类里最好的数据库。需要说明的是,该数据库需要技术人员或开发人员使用,因为里面有格式针对每一句的翻译或解决,具体可以从文后的样本链接下载......
  • react项目在不暴露配置文件的情况下配置环境变量
    react项目在不暴露配置文件的情况下修改打包配置需要用到 react-app-rewired和customize-cra包对打包配置文件进行修改。 添加自定义环境变量有两种方法:方法1:使用dotenv-cli1、运行 yarnglobaladddotenv-cli 全局安装dotenv-cli2、在根目录下添加.env.pre文件,写入变......
  • 以圆类Circle及立体图形类Solid为基础设计圆柱类Cylinder
    以点类Point及平面图形类Plane为基类公有派生圆类Circle,再以圆类Circle及立体图形类Solid为基类公有派生圆柱类Cylinder,main(void)函数完成对圆柱类Cylinder的测试。Point类结构说明: Point类的数据成员包括:①私有数据成员:X坐标x(double型),Y坐标y(double型)。Point类成员函数......
  • 2步轻松实现ASP.NET Core托管服务执行定时任务
    最近接到一个新项目,需要在项目里添加一个后台任务,定时去发邮件通知客户;由于是一个比较小型的项目,不希望引入Quartz.Net、Hangfire等太重的框架,同时也没持久化要;寻觅了一下发现ASP.NETCore本身带有托管服务,可以执行定时任务。ASP.NETCore提供了IHostedService接口,它使我们能够创......
  • 基于FPGA的HDB3编译码verilog实现,包括testbench
    1.算法仿真效果vivado2019.2仿真结果如下:  2.算法涉及理论知识概要       数字基带信号的传输是数字通信系统的重要组成部分。在数字通信中,有些场合可不经过载波调制和解调过程,而对基带信号进行直接传输。采用AMI码的信号交替反转,有可能出现四连零现象,这不利于接......
  • m基于MIMO-OFDM-LDPC-STBC的通信链路matlab误码率仿真
    1.算法仿真效果matlab2013b仿真结果如下:使用一个二值图进行测试,并加入不同的均衡算法进行对比:2.算法涉及理论知识概要LDPC码是麻省理工学院RobertGallager于1963年在博士论文中提出的一种具有稀疏校验矩阵的分组纠错码。几乎适用于所有的信道,因此成为编码界近年来的研究......
  • Ad Hoc Distributed Queries 的启用与关闭2
    上一篇的解决办法,主要是通过语句操作来完成,SQLServer也提供了图形操作界面来解决类似问题我们可以利用SQLServer(2005)配置工具中提供的“SQLServer外围应用配置”来完成此操作,具体的操作方法如下:1.打开“SQLServer外围应用配置”,界面如下图 2.选择“SQLServer外围应用配置......
  • Docker如何上传本地文件到容器目录?
    先贴上命令:dockercp本地文件路径ID全称:容器路径下面来举个例子:我要把本地电脑的mysql-connector-java-5.1.46.jar上传到Linux下Docker里面的logstash容器下的/usr/share/logstash/lib目录。1.首先使用ssh工具上传jar包到Linux的/usr/local目录:2.使用docker命令赋值到docker容器......
  • JavaScript正则获取a标签中的path路径值-流程引擎-计算引擎
    直接上代码://获取附件中的链接地址functionget_file_path_from_encode_value(x){vararrLink=[];x.replace(/<a[^>]*path=['"]([^'"]+)[^>]*/gi,function(match,capture){arr......
  • m基于MIMO-OFDM-LDPC-STBC的通信链路matlab误码率仿真
    1.算法仿真效果matlab2013b仿真结果如下:    使用一个二值图进行测试,并加入不同的均衡算法进行对比:  2.算法涉及理论知识概要          LDPC码是麻省理工学院RobertGallager于1963年在博士论文中提出的一种具有稀疏校验矩阵的分组纠错码。几乎......