C#语言的23种设计模式

C# 作为面向对象编程语言,可实现经典的 23 种设计模式(GoF 设计模式)。这些模式分为三大类:创建型结构型行为型。以下是每种模式的简要介绍和 C# 实现示例。

一、创建型模式(Creational Patterns)

1. 单例模式(Singleton)

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

public sealed class Singleton
{
    private static readonly Lazy<Singleton> instance = 
        new Lazy<Singleton>(() => new Singleton());
    public static Singleton Instance => instance.Value;
    private Singleton() { } // 私有构造函数
}
2. 工厂方法模式(Factory Method)

定义创建对象的接口,让子类决定实例化哪个类。

public interface IProduct { void Operation(); }
public class ConcreteProductA : IProduct { ... }
public class ConcreteProductB : IProduct { ... }

public abstract class Creator
{
    public abstract IProduct FactoryMethod();
}

public class ConcreteCreatorA : Creator
{
    public override IProduct FactoryMethod() => new ConcreteProductA();
}
3. 抽象工厂模式(Abstract Factory)

提供创建一系列相关对象的接口,无需指定具体类。

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

public class ConcreteFactory1 : IAbstractFactory
{
    public IProductA CreateProductA() => new ProductA1();
    public IProductB CreateProductB() => new ProductB1();
}
4. 建造者模式(Builder)

将复杂对象的构建与表示分离,使同样的构建过程可以创建不同的表示。

public class Car
{
    public string Engine { get; set; }
    public string Wheels { get; set; }
}

public interface ICarBuilder
{
    void BuildEngine();
    void BuildWheels();
    Car GetResult();
}

public class SportsCarBuilder : ICarBuilder { ... }
5. 原型模式(Prototype)

通过复制现有实例创建新对象,无需知道创建细节。

public interface IPrototype
{
    IPrototype Clone();
}

public class ConcretePrototype : IPrototype
{
    public int Value { get; set; }
    public IPrototype Clone() => new ConcretePrototype { Value = this.Value };
}

二、结构型模式(Structural Patterns)

6. 适配器模式(Adapter)

将一个类的接口转换成客户希望的另一个接口,使不兼容的类能一起工作。

// 目标接口
public interface ITarget { void Request(); }

// 适配者类
public class Adaptee { public void SpecificRequest() { } }

// 适配器
public class Adapter : ITarget
{
    private readonly Adaptee adaptee = new Adaptee();
    public void Request() => adaptee.SpecificRequest();
}
7. 桥接模式(Bridge)

将抽象部分与实现部分分离,使它们可以独立变化。

public interface IColor { string Fill(); }
public class Red : IColor { public string Fill() => "Red"; }

public abstract class Shape
{
    protected IColor color;
    public Shape(IColor color) => this.color = color;
    public abstract string Draw();
}

public class Circle : Shape
{
    public Circle(IColor color) : base(color) { }
    public override string Draw() => $"Circle filled with {color.Fill()}";
}
8. 组合模式(Composite)

将对象组合成树形结构以表示 “部分 - 整体” 的层次结构。

public abstract class Component
{
    public abstract void Operation();
    public virtual void Add(Component component) { }
    public virtual void Remove(Component component) { }
}

public class Composite : Component
{
    private readonly List<Component> children = new List<Component>();
    public override void Operation() => children.ForEach(c => c.Operation());
    public override void Add(Component component) => children.Add(component);
}
9. 装饰器模式(Decorator)

动态地给对象添加额外职责,比继承更灵活。

public interface IComponent { void Operation(); }

public class ConcreteComponent : IComponent { ... }

public abstract class Decorator : IComponent
{
    protected IComponent component;
    public Decorator(IComponent component) => this.component = component;
    public virtual void Operation() => component.Operation();
}

public class ConcreteDecoratorA : Decorator { ... }
10. 外观模式(Facade)

为子系统中的一组接口提供统一的高层接口,简化客户端调用。

public class SubsystemA { public void OperationA() { } }
public class SubsystemB { public void OperationB() { } }

public class Facade
{
    private readonly SubsystemA subsystemA = new SubsystemA();
    private readonly SubsystemB subsystemB = new SubsystemB();
    public void Operation()
    {
        subsystemA.OperationA();
        subsystemB.OperationB();
    }
}
11. 享元模式(Flyweight)

通过共享技术有效地支持大量细粒度的对象。

public interface ICharacter
{
    void Display(int fontSize);
}

public class CharacterA : ICharacter
{
    private readonly char symbol = 'A';
    public void Display(int fontSize) => Console.WriteLine($"{symbol} (size: {fontSize})");
}

public class CharacterFactory
{
    private readonly Dictionary<char, ICharacter> characters = new Dictionary<char, ICharacter>();
    public ICharacter GetCharacter(char key)
    {
        if (!characters.ContainsKey(key))
            characters[key] = new CharacterA(); // 根据 key 创建具体字符
        return characters[key];
    }
}
12. 代理模式(Proxy)

为其他对象提供一种代理以控制对这个对象的访问。

public interface ISubject { void Request(); }

public class RealSubject : ISubject { public void Request() { } }

public class Proxy : ISubject
{
    private RealSubject realSubject;
    public void Request()
    {
        if (realSubject == null)
            realSubject = new RealSubject();
        realSubject.Request();
    }
}

三、行为型模式(Behavioral Patterns)

13. 责任链模式(Chain of Responsibility)

将请求的发送者和接收者解耦,使多个对象都有机会处理请求。

public abstract class Handler
{
    protected Handler successor;
    public void SetSuccessor(Handler successor) => this.successor = successor;
    public abstract void HandleRequest(int request);
}

public class ConcreteHandler1 : Handler
{
    public override void HandleRequest(int request)
    {
        if (request <= 10)
            Console.WriteLine($"Handled by ConcreteHandler1: {request}");
        else if (successor != null)
            successor.HandleRequest(request);
    }
}
14. 命令模式(Command)

将请求封装为对象,使你可以用不同的请求对客户进行参数化。

public interface ICommand { void Execute(); }

public class Receiver { public void Action() { } }

public class ConcreteCommand : ICommand
{
    private readonly Receiver receiver;
    public ConcreteCommand(Receiver receiver) => this.receiver = receiver;
    public void Execute() => receiver.Action();
}
15. 解释器模式(Interpreter)

给定一个语言,定义它的文法表示,并定义一个解释器。

public interface IExpression
{
    int Interpret();
}

public class Number : IExpression
{
    private readonly int number;
    public Number(int number) => this.number = number;
    public int Interpret() => number;
}

public class Add : IExpression
{
    private readonly IExpression left;
    private readonly IExpression right;
    public Add(IExpression left, IExpression right) => (this.left, this.right) = (left, right);
    public int Interpret() => left.Interpret() + right.Interpret();
}
16. 迭代器模式(Iterator)

提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露该对象的内部表示。

public interface IIterator<T>
{
    bool HasNext();
    T Next();
}

public interface IAggregate<T>
{
    IIterator<T> CreateIterator();
}

public class ConcreteAggregate<T> : IAggregate<T>
{
    private readonly List<T> items = new List<T>();
    public IIterator<T> CreateIterator() => new ConcreteIterator<T>(items);
}
17. 中介者模式(Mediator)

用一个中介对象来封装一系列的对象交互,使各对象不需要显式地相互引用。

public interface IMediator
{
    void Send(string message, Colleague colleague);
}

public class ConcreteMediator : IMediator
{
    private ConcreteColleague1 colleague1;
    private ConcreteColleague2 colleague2;
    public void Send(string message, Colleague colleague)
    {
        if (colleague == colleague1)
            colleague2.Notify(message);
        else
            colleague1.Notify(message);
    }
}
18. 备忘录模式(Memento)

在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。

public class Memento
{
    public string State { get; }
    public Memento(string state) => State = state;
}

public class Originator
{
    private string state;
    public Memento CreateMemento() => new Memento(state);
    public void RestoreMemento(Memento memento) => state = memento.State;
}
19. 观察者模式(Observer)

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

public interface IObserver { void Update(string message); }

public interface ISubject
{
    void Attach(IObserver observer);
    void Detach(IObserver observer);
    void Notify();
}

public class ConcreteSubject : ISubject { ... }
20. 状态模式(State)

允许对象在其内部状态改变时改变它的行为,对象看起来似乎修改了它的类。

public interface IState
{
    void Handle(Context context);
}

public class ConcreteStateA : IState
{
    public void Handle(Context context) => context.State = new ConcreteStateB();
}

public class Context
{
    private IState state;
    public IState State
    {
        get => state;
        set
        {
            state = value;
            Console.WriteLine($"State changed to {state.GetType().Name}");
        }
    }
}
21. 策略模式(Strategy)

定义一系列算法,将每个算法封装起来,并使它们可以相互替换。

public interface IStrategy { void Execute(); }

public class ConcreteStrategyA : IStrategy { ... }
public class ConcreteStrategyB : IStrategy { ... }

public class Context
{
    private IStrategy strategy;
    public Context(IStrategy strategy) => this.strategy = strategy;
    public void ExecuteStrategy() => strategy.Execute();
}
22. 模板方法模式(Template Method)

定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。

public abstract class AbstractClass
{
    public void TemplateMethod()
    {
        BaseOperation1();
        RequiredOperations1();
        BaseOperation2();
        Hook();
    }

    protected void BaseOperation1() { }
    protected void BaseOperation2() { }
    protected abstract void RequiredOperations1();
    protected virtual void Hook() { }
}
23. 访问者模式(Visitor)

表示一个作用于某对象结构中的各元素的操作,它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。

public interface IVisitor
{
    void VisitConcreteElementA(ConcreteElementA element);
    void VisitConcreteElementB(ConcreteElementB element);
}

public interface IElement
{
    void Accept(IVisitor visitor);
}

public class ConcreteElementA : IElement
{
    public void Accept(IVisitor visitor) => visitor.VisitConcreteElementA(this);
}

总结

设计模式的核心价值在于复用性可维护性。C# 提供了强大的面向对象特性(如接口、抽象类、委托)和语言特性(如泛型、LINQ),使得实现这些模式更加简洁高效。实际应用中,应根据具体场景选择合适的模式,避免过度设计。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值