file-type

掌握设计模式:23种设计模式的C#实现代码解析

3星 · 超过75%的资源 | 下载需积分: 3 | 15KB | 更新于2025-07-10 | 129 浏览量 | 18 下载量 举报 收藏
download 立即下载
设计模式是软件工程中用于解决特定问题的一套已验证的解决方案模板。它们代表了软件开发社区在多年的项目实践中积累的设计经验。通过使用设计模式,开发者可以编写出更加灵活和可维护的代码,同时提高了代码的可复用性。设计模式分为三大类:创建型模式、结构型模式和行为型模式。 以下是23个设计模式的详细介绍,按照其分类进行阐述,并且会提供每种模式的核心概念以及在C#中的可能实现方式。 1. 创建型模式 创建型模式主要涉及对象实例化的过程,它们用于创建对象的同时隐藏创建逻辑,而不是使用new直接实例化对象。这样可以提高系统的灵活性和可复用性。 - 单例模式(Singleton) 单例模式确保一个类只有一个实例,并提供一个全局访问点。C#实现时通常使用私有构造函数和一个静态的实例变量。 ```csharp public sealed class Singleton { private static Singleton instance = new Singleton(); private Singleton() { } public static Singleton Instance { get { return instance; } } } ``` - 建造者模式(Builder) 建造者模式将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。C#中可以使用抽象类定义产品结构,并通过一个指挥者类控制建造过程。 - 原型模式(Prototype) 原型模式通过复制一个已有的对象来创建一个新的对象,这样可以不必知道对象创建的细节。C#中通常通过实现ICloneable接口来实现原型模式。 ```csharp public class Prototype : ICloneable { public int Value { get; set; } public object Clone() { return this.MemberwiseClone(); } } ``` - 工厂方法模式(Factory Method) 工厂方法模式定义了一个创建对象的接口,但由子类决定要实例化的类是哪一个。C#中通过定义一个抽象类或接口来表示产品,并在子类中重写创建产品的逻辑。 ```csharp public abstract class Product { } public class ConcreteProduct : Product { } public abstract class Creator { public abstract Product FactoryMethod(); } public class ConcreteCreator : Creator { public override Product FactoryMethod() { return new ConcreteProduct(); } } ``` - 抽象工厂模式(Abstract Factory) 抽象工厂模式提供一个接口用于创建相关或依赖对象的家族,而不需要明确指定具体类。C#实现时使用多个工厂方法来创建不同类型的对象。 ```csharp public interface IAbstractFactory { ProductA CreateProductA(); ProductB CreateProductB(); } public class ConcreteFactoryA : IAbstractFactory { public ProductA CreateProductA() { return new ConcreteProductA(); } public ProductB CreateProductB() { return new ConcreteProductB(); } } ``` 2. 结构型模式 结构型模式涉及如何组合类和对象以获得更大的结构。结构型模式主要用于组织类或对象以形成更大的结构。 - 适配器模式(Adapter) 适配器模式允许将一个类的接口转换成客户期望的另一个接口,适配器让原本接口不兼容的类可以合作无间。C#中可以使用一个适配器类来包装一个类或接口,并提供新接口的实现。 ```csharp public class Adaptee { public void SpecificMethod() { // ... } } public interface ITarget { void AdaptedMethod(); } public class Adapter : ITarget { private Adaptee adaptee = new Adaptee(); public void AdaptedMethod() { adaptee.SpecificMethod(); } } ``` - 桥接模式(Bridge) 桥接模式将抽象部分与实现部分分离,使它们都可以独立地变化。C#中通过使用聚合关系而不是继承关系,将抽象和实现分离。 ```csharp public abstract class Abstraction { protected Implementor implementor; public Abstraction(Implementor implementor) { this.implementor = implementor; } public virtual void Operation() { implementor.OperationImp(); } } public class RefinedAbstraction : Abstraction { public RefinedAbstraction(Implementor implementor) : base(implementor) { } public override void Operation() { implementor.OperationImp(); } } public abstract class Implementor { public abstract void OperationImp(); } public class ConcreteImplementorA : Implementor { public override void OperationImp() { // ... } } ``` - 组合模式(Composite) 组合模式将对象组合成树形结构以表示“部分-整体”的层次结构。组合使得用户对单个对象和组合对象的使用具有一致性。C#中可以通过定义一个组合节点接口,并使用递归的方式来管理子节点。 ```csharp public interface IComponent { void Operation(); void Add(IComponent component); void Remove(IComponent component); } public class Leaf : IComponent { public void Operation() { // ... } public void Add(IComponent component) { /* ... */ } public void Remove(IComponent component) { /* ... */ } } public class Composite : IComponent { private List<IComponent> _children = new List<IComponent>(); public void Add(IComponent component) { _children.Add(component); } public void Remove(IComponent component) { _children.Remove(component); } public void Operation() { foreach (var child in _children) { child.Operation(); } } } ``` - 装饰器模式(Decorator) 装饰器模式动态地给一个对象添加一些额外的职责,就增加功能来说,装饰器比生成子类更为灵活。C#中可以通过定义一个抽象组件类和一个抽象装饰类,并让具体装饰类持有组件类的实例。 ```csharp public abstract class Component { public abstract void Operation(); } public class ConcreteComponent : Component { public override void Operation() { // ... } } public abstract class Decorator : Component { protected Component component; public Decorator(Component component) { this.component = component; } public override void Operation() { component.Operation(); } } public class ConcreteDecorator : Decorator { public ConcreteDecorator(Component component) : base(component) { } public override void Operation() { base.Operation(); AddedBehavior(); } private void AddedBehavior() { /* ... */ } } ``` - 外观模式(Facade) 外观模式为子系统中的一组接口提供一个统一的高层接口,以使子系统更容易使用。C#实现时可以定义一个外观类,该类提供一个接口来客户端请求的子系统的一系列接口。 ```csharp public class SubsystemA { /* ... */ } public class SubsystemB { /* ... */ } public class SubsystemC { /* ... */ } public class Facade { private SubsystemA subsystemA = new SubsystemA(); private SubsystemB subsystemB = new SubsystemB(); private SubsystemC subsystemC = new SubsystemC(); public void Operation() { subsystemA.Operation(); subsystemB.Operation(); subsystemC.Operation(); } } ``` - 享元模式(Flyweight) 享元模式通过共享来支持大量细粒度对象的复用,从而减少创建对象的开销。享元可以是纯享元,也可以是带状态的享元,C#中可以使用类结构来区分这两种享元,并通过享元工厂来管理享元的创建和复用。 ```csharp public interface IFlyweight { void Operation(string extrinsicState); } public class ConcreteFlyweight : IFlyweight { public void Operation(string extrinsicState) { // ... } } public class FlyweightFactory { private Dictionary<string, IFlyweight> flyweights = new Dictionary<string, IFlyweight>(); public IFlyweight GetFlyweight(string key) { if (!flyweights.ContainsKey(key)) { flyweights[key] = new ConcreteFlyweight(); } return flyweights[key]; } } ``` - 代理模式(Proxy) 代理模式为其他对象提供一种代理以控制对这个对象的访问。代理类和委托类实现同样的接口,并在代理类中控制对委托类的实例化和访问。C#中可以使用类或接口实现代理模式。 ```csharp public interface IService { void Operation(); } public class Service : IService { public void Operation() { // ... } } public class ServiceProxy : IService { private IService _service; public void Operation() { if (_service == null) { _service = new Service(); } _service.Operation(); } } ``` 3. 行为型模式 行为型模式专注于对象之间的通信,它们描述了对象之间的交云模型和职责分配。 - 责任链模式(Chain of Responsibility) 责任链模式是使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合。C#中可以使用链表或对象集合来创建请求链,每个处理者都有下一个处理者的引用。 ```csharp public abstract class Handler { protected Handler successor; public void SetSuccessor(Handler successor) { this.successor = successor; } public abstract void HandleRequest(Request request); } public class ConcreteHandler : Handler { public override void HandleRequest(Request request) { if (CanHandle(request)) { // Handle the request here } else if (successor != null) { successor.HandleRequest(request); } } private bool CanHandle(Request request) { // ... return true; } } ``` - 命令模式(Command) 命令模式将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。C#中使用命令接口和一系列具体命令类来实现。 ```csharp public interface ICommand { void Execute(); } public class ConcreteCommand : ICommand { private Receiver receiver; public ConcreteCommand(Receiver receiver) { this.receiver = receiver; } public void Execute() { receiver.Action(); } } public class Receiver { public void Action() { // ... } } ``` - 解释器模式(Interpreter) 解释器模式给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。C#中使用类和接口表示文法。 ```csharp public interface IExpression { bool Interpret(string context); } public class TerminalExpression : IExpression { public bool Interpret(string context) { // Implement interpretation logic return true; } } public class NonterminalExpression : IExpression { private IExpression firstExpression; private IExpression secondExpression; public bool Interpret(string context) { // Implement interpretation logic return true; } } ``` - 迭代器模式(Iterator) 迭代器模式提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露该对象的内部表示。C#中通过实现IIterator接口和聚合接口。 ```csharp public interface IIterator { bool hasNext(); object next(); } public interface IAggregate { IIterator CreateIterator(); } public class ConcreteIterator : IIterator { // Implement IIterator methods } public class ConcreteAggregate : IAggregate { public IIterator CreateIterator() { return new ConcreteIterator(this); } } ``` - 中介者模式(Mediator) 中介者模式用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。C#中通过定义一个中介者类来协调对象间的通信。 ```csharp public interface IMediator { void Send(string message, Colleague colleague); } public abstract class Colleague { protected IMediator mediator; public Colleague(IMediator mediator) { this.mediator = mediator; } public abstract void Send(string message); public abstract void Receive(string message); } ``` - 备忘录模式(Memento) 备忘录模式在不破坏封装的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。C#中使用备忘录类来保存对象状态。 ```csharp public class Originator { private string state; public string State { get { return state; } set { state = value; } } public Memento CreateMemento() { return new Memento(state); } public void SetMemento(Memento memento) { state = memento.GetState(); } } public class Memento { private string state; public Memento(string stateToSave) { state = stateToSave; } public string GetState() { return state; } } ``` - 观察者模式(Observer) 观察者模式定义了对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。C#中使用接口来定义观察者和主题。 ```csharp public interface IObserver { void Update(IObservable o, object arg); } public interface IObservable { void Attach(IObserver observer); void Detach(IObserver observer); void Notify(); } public class ConcreteSubject : IObservable { private List<IObserver> _observers = new List<IObserver>(); public void Attach(IObserver observer) { _observers.Add(observer); } public void Detach(IObserver observer) { _observers.Remove(observer); } public void Notify() { foreach (var observer in _observers) { observer.Update(this, null); } } } ``` - 状态模式(State) 状态模式允许一个对象在其内部状态改变时改变它的行为,对象看起来似乎修改了它的类。C#中通过定义状态接口和一系列具体状态类来实现。 ```csharp public interface IState { void Handle(); } public class ConcreteStateA : IState { public void Handle() { // Handle state A } } public class Context { private IState _state; public Context(IState state) { _state = state; } public void Request() { _state.Handle(); } public void SetState(IState state) { _state = state; } } ``` - 策略模式(Strategy) 策略模式定义了一系列算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法的变化独立于使用算法的客户。C#中可以定义一个策略接口和一系列具体策略类。 ```csharp public interface IStrategy { void AlgorithmInterface(); } public class ConcreteStrategyA : IStrategy { public void AlgorithmInterface() { // Implement algorithm A } } public class Context { private IStrategy _strategy; public Context(IStrategy strategy) { _strategy = strategy; } public void SetStrategy(IStrategy strategy) { _strategy = strategy; } public void AlgorithmInterface() { _strategy.AlgorithmInterface(); } } ``` - 模板方法模式(Template Method) 模板方法模式在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤。C#中通过在抽象类中定义一个模板方法,并在子类中重写它。 ```csharp public abstract class AbstractClass { public void TemplateMethod() { PrimitiveOperation1(); PrimitiveOperation2(); // ... } protected abstract void PrimitiveOperation1(); protected abstract void PrimitiveOperation2(); } public class ConcreteClass : AbstractClass { protected override void PrimitiveOperation1() { // Implement primitive operation } protected override void PrimitiveOperation2() { // Implement primitive operation } } ``` - 访问者模式(Visitor) 访问者模式表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。C#中通过定义访问者接口和具体的访问者类来实现。 ```csharp public interface IVisitor { void VisitConcreteElementA(ConcreteElementA elementA); void VisitConcreteElementB(ConcreteElementB elementB); } public interface IElement { void Accept(IVisitor visitor); } public class ConcreteElementA : IElement { public void Accept(IVisitor visitor) { visitor.VisitConcreteElementA(this); } } public class ConcreteElementB : IElement { public void Accept(IVisitor visitor) { visitor.VisitConcreteElementB(this); } } ``` 以上介绍的23个设计模式对于软件开发具有重要意义,它们提供了一系列经过验证的解决方案,使得开发者可以在面对各种设计挑战时更加得心应手。通过应用这些设计模式,不仅可以提高软件的可维护性、可复用性,还能增强软件的可扩展性和灵活性。

相关推荐