C# 常用设计模式有哪些

发布时间 2023-05-23 13:02:20作者: 那年十八岁
原文地址: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 }

 

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