23种设计模式

1 单例模式 (Singleton Pattern)

单例模式确保一个类只有一个实例。例如,一个全局的配置管理器类,它负责管理应用程序的配置设置。

using System;

public sealed class Singleton
{
    private static Singleton instance;
    private Singleton() { }

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

    public void PrintMessage()
    {
        Console.WriteLine("Hello from Singleton!");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Singleton singleton1 = Singleton.Instance;
        Singleton singleton2 = Singleton.Instance;

        Console.WriteLine(singleton1 == singleton2); // 输出:True,表示两者是同一个实例

        singleton1.PrintMessage(); // 输出:Hello from Singleton!
    }
}

2.工厂模式 (Factory Pattern)

工厂模式用于创建对象,例如,一个抽象的工厂类可以派生出不同类型的工厂,以创建不同种类的产品对象。

using System;

public interface IProduct
{
    void Create();
}

public class ConcreteProductA : IProduct
{
    public void Create()
    {
        Console.WriteLine("Product A is created.");
    }
}

public class ConcreteProductB : IProduct
{
    public void Create()
    {
        Console.WriteLine("Product B is created.");
    }
}

public class Factory
{
    public IProduct CreateProduct(string type)
    {
        switch (type)
        {
            case "A":
                return new ConcreteProductA();
            case "B":
                return new ConcreteProductB();
            default:
                throw new ArgumentException("Invalid product type");
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Factory factory = new Factory();
        IProduct productA = factory.CreateProduct("A");
        IProduct productB = factory.CreateProduct("B");

        productA.Create(); // 输出:Product A is created.
        productB.Create(); // 输出:Product B is created.
    }
}

3.观察者模式 (Observer Pattern)

观察者模式用于建立对象之间的一对多依赖关系。例如,一个天气数据主题通知多个天气观察者。

using System;
using System.Collections.Generic;

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

public class ConcreteObserver : IObserver
{
    private string name;

    public ConcreteObserver(string name)
    {
        this.name = name;
    }

    public void Update(string message)
    {
        Console.WriteLine($"{name} received message: {message}");
    }
}

public class Subject
{
    private List<IObserver> observers = new List<IObserver>();

    public void RegisterObserver(IObserver observer)
    {
        observers.Add(observer);
    }

    public void NotifyObservers(string message)
    {
        foreach (IObserver observer in observers)
        {
            observer.Update(message);
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Subject subject = new Subject();

        IObserver observer1 = new ConcreteObserver("Observer 1");
        IObserver observer2 = new ConcreteObserver("Observer 2");

        subject.RegisterObserver(observer1);
        subject.RegisterObserver(observer2);

        subject.NotifyObservers("Hello, observers!");
    }
}

4.策略模式 (Strategy Pattern)

策略模式定义一系列算法,允许客户端在运行时选择要使用的算法。例如,一个排序器类,它可以接受不同的排序策略。

using System;

public interface IStrategy
{
    void Execute();
}

public class ConcreteStrategyA : IStrategy
{
    public void Execute()
    {
        Console.WriteLine("Executing Strategy A");
    }
}

public class ConcreteStrategyB : IStrategy
{
    public void Execute()
    {
        Console.WriteLine("Executing Strategy B");
    }
}

public class Context
{
    private IStrategy strategy;

    public Context(IStrategy strategy)
    {
        this.strategy = strategy;
    }

    public void ExecuteStrategy()
    {
        strategy.Execute();
    }
}

class Program
{
    static void Main(string[] args)
    {
        IStrategy strategyA = new ConcreteStrategyA();
        IStrategy strategyB = new ConcreteStrategyB();

        Context contextA = new Context(strategyA);
        Context contextB = new Context(strategyB);

        contextA.ExecuteStrategy(); // 输出:Executing Strategy A
        contextB.ExecuteStrategy(); // 输出:Executing Strategy B
    }
}

5.装饰器模式 (Decorator Pattern)

装饰器模式允许你动态地添加功能到对象,不需要修改其原始类。例如,可以使用装饰器模式来添加日志记录、验证或缓存功能。

using System;

public interface IComponent
{
    void Operation();
}

public class ConcreteComponent : IComponent
{
    public void Operation()
    {
        Console.WriteLine("ConcreteComponent operation.");
    }
}

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
{
    public ConcreteDecoratorA(IComponent component) : base(component) { }

    public override void Operation()
    {
        base.Operation();
        Console.WriteLine("ConcreteDecoratorA operation.");
    }
}

public class ConcreteDecoratorB : Decorator
{
    public ConcreteDecoratorB(IComponent component) : base(component) { }

    public override void Operation()
    {
        base.Operation();
        Console.WriteLine("ConcreteDecoratorB operation.");
    }
}

class Program
{
    static void Main(string[] args)
    {
        IComponent component = new ConcreteComponent();
        IComponent decoratedComponentA = new ConcreteDecoratorA(component);
        IComponent decoratedComponentB = new ConcreteDecoratorB(component);

        component.Operation();        // 输出:ConcreteComponent operation.
        decoratedComponentA.Operation(); // 输出:ConcreteComponent operation. \n ConcreteDecoratorA operation.
        decoratedComponentB.Operation(); // 输出:ConcreteComponent operation. \n ConcreteDecoratorB operation.
    }
}

6.命令模式 (Command Pattern)

命令模式将请求封装成对象,允许参数化客户端对象操作,并支持撤销操作。假设你正在开发一个遥控器应用,它可以控制不同设备(例如电视、音响、灯等)

// 命令接口
public interface ICommand
{
    void Execute();
}

// 具体命令类,每个命令对应一个设备的操作
public class TurnOnTVCommand : ICommand
{
    private TV tv;

    public TurnOnTVCommand(TV tv)
    {
        this.tv = tv;
    }

    public void Execute()
    {
        tv.TurnOn();
    }
}

public class TurnOffTVCommand : ICommand
{
    private TV tv;

    public TurnOffTVCommand(TV tv)
    {
        this.tv = tv;
    }

    public void Execute()
    {
        tv.TurnOff();
    }
}
// 设备类,例如电视
public class TV
{
    public void TurnOn()
    {
        Console.WriteLine("TV is turned on.");
    }

    public void TurnOff()
    {
        Console.WriteLine("TV is turned off.");
    }
}

// 遥控器类,负责执行命令
public class RemoteControl
{
    private ICommand command;

    public void SetCommand(ICommand command)
    {
        this.command = command;
    }

    public void PressButton()
    {
        command.Execute();
    }
}

class Program
{
    static void Main(string[] args)
    {
       TV tv = new TV();
	   ICommand turnOnCommand = new TurnOnTVCommand(tv);
	   ICommand turnOffCommand = new TurnOffTVCommand(tv);

	   RemoteControl remote = new RemoteControl();
	   remote.SetCommand(turnOnCommand);
	   remote.PressButton(); // 打开电视

	   remote.SetCommand(turnOffCommand);
	   remote.PressButton(); // 关闭电视
    }
}

7.适配器模式 (Adapter Pattern)

适配器模式用于将一个接口转换成另一个接口,以便对象可以与其他对象交互。例如,可以使用适配器模式来使现有类与新接口兼容。

public interface INewInterface
{
    void NewMethod();
}

public class OldClass
{
    public void OldMethod() { Console.WriteLine("Old method."); }
}

public class Adapter : INewInterface
{
    private OldClass oldObject;

    public Adapter(OldClass oldObject)
    {
        this.oldObject = oldObject;
    }

    public void NewMethod()
    {
        oldObject.OldMethod();
    }
}
class Program
{
    static void Main(string[] args)
    {
        OldClass adaptee = new OldClass();
        Adapter target = new Adapter (adaptee);
        target.NewMethod(); // 输出:Old method.
    }
}

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

模板方法模式定义了一个算法的骨架,其中一些步骤延迟到子类中实现。这允许子类在不改变算法结构的情况下重新定义算法的特定步骤。

using System;

public abstract class AbstractClass
{
    public void TemplateMethod()
    {
        Console.WriteLine("AbstractClass: Doing something before calling a hook.");
        Hook();
        Console.WriteLine("AbstractClass: Doing something after calling a hook.");
    }

    protected abstract void Hook();
}

public class ConcreteClassA : AbstractClass
{
    protected override void Hook()
    {
        Console.WriteLine("ConcreteClassA's hook implementation.");
    }
}

public class ConcreteClassB : AbstractClass
{
    protected override void Hook()
    {
        Console.WriteLine("ConcreteClassB's hook implementation.");
    }
}

class Program
{
    static void Main(string[] args)
    {
        AbstractClass classA = new ConcreteClassA();
        AbstractClass classB = new ConcreteClassB();

        classA.TemplateMethod();
        classB.TemplateMethod();
    }
}

9.状态模式 (State Pattern)

状态模式允许对象在内部状态改变时改变其行为。状态模式通过将状态抽象为单独的类来实现,使状态转换更加清晰。

using System;

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

public class ConcreteStateA : IState
{
    public void HandleState(Context context)
    {
        Console.WriteLine("Handling state A.");
        context.State = new ConcreteStateB();
    }
}

public class ConcreteStateB : IState
{
    public void HandleState(Context context)
    {
        Console.WriteLine("Handling state B.");
        context.State = new ConcreteStateA();
    }
}

public class Context
{
    public IState State { get; set; }

    public void Request()
    {
        State.HandleState(this);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Context context = new Context();
        context.State = new ConcreteStateA();

        context.Request(); // 输出:Handling state A.
        context.Request(); // 输出:Handling state B.
        context.Request(); // 输出:Handling state A.
    }
}

10.代理模式 (Proxy Pattern)

代理模式用于控制对其他对象的访问。它为其他对象提供了一个代理,以控制对这些对象的访问。

public interface IImage
{
    void Display();
}

public class RealImage : IImage
{
    private string filename;

    public RealImage(string filename)
    {
        this.filename = filename;
        LoadImageFromDisk();
    }

    public void Display()
    {
        Console.WriteLine("Displaying image: " + filename);
    }

    private void LoadImageFromDisk()
    {
        Console.WriteLine("Loading image: " + filename);
    }
}

public class ProxyImage : IImage
{
    private RealImage realImage;
    private string filename;

    public ProxyImage(string filename)
    {
        this.filename = filename;
    }

    public void Display()
    {
        if (realImage == null)
        {
            realImage = new RealImage(filename);
        }
        realImage.Display();
    }
}

class Program
{
    static void Main(string[] args)
    {
        IImage image = new ProxyImage("test.jpg");
		// 图像将在此点加载
		image.Display();
		// 图像不会重新加载,因为它已经被代理加载过
		image.Display();
    }
}

11.责任链模式 (Chain of Responsibility Pattern)

责任链模式用于构建处理请求的对象链。每个对象决定是否处理请求或将其传递给链中的下一个对象。

public abstract class Handler
{
    protected Handler successor;

    public void SetSuccessor(Handler successor)
    {
        this.successor = successor;
    }

    public abstract void HandleRequest(int request);
}

public class ConcreteHandlerA : Handler
{
    public override void HandleRequest(int request)
    {
        if (request < 10)
        {
            Console.WriteLine("Handled by ConcreteHandlerA");
        }
        else if (successor != null)
        {
            successor.HandleRequest(request);
        }
    }
}

public class ConcreteHandlerB : Handler
{
    public override void HandleRequest(int request)
    {
        if (request >= 10 && request < 20)
        {
            Console.WriteLine("Handled by ConcreteHandlerB");
        }
        else if (successor != null)
        {
            successor.HandleRequest(request);
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Handler handlerA = new ConcreteHandlerA();
		Handler handlerB = new ConcreteHandlerB();

		handlerA.SetSuccessor(handlerB);

		handlerA.HandleRequest(5);   // 输出:Handled by ConcreteHandlerA
		handlerA.HandleRequest(15);  // 输出:Handled by ConcreteHandlerB
		handlerA.HandleRequest(25);  // 输出:Request not handled
    }
}

12.访问者模式 (Visitor Pattern)

访问者模式用于在不改变对象结构的情况下添加新操作。它将操作与对象分离,允许你在不修改对象的类的情况下添加新功能。

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

public abstract class Element
{
    public abstract void Accept(IVisitor visitor);
}

public class ConcreteElementA : Element
{
    public override void Accept(IVisitor visitor)
    {
        visitor.Visit(this);
    }
}

public class ConcreteElementB : Element
{
    public override void Accept(IVisitor visitor)
    {
        visitor.Visit(this);
    }
}

public class ConcreteVisitor : IVisitor
{
    public void Visit(ConcreteElementA element)
    {
        Console.WriteLine("Visitor is processing ConcreteElementA.");
    }

    public void Visit(ConcreteElementB element)
    {
        Console.WriteLine("Visitor is processing ConcreteElementB.");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Element elementA = new ConcreteElementA();
		Element elementB = new ConcreteElementB();
		IVisitor visitor = new ConcreteVisitor();

		elementA.Accept(visitor);  // 输出:Visitor is processing ConcreteElementA.
		elementB.Accept(visitor);  // 输出:Visitor is processing ConcreteElementB.
    }
}

13.备忘录模式 (Memento Pattern)

备忘录模式的主要作用是允许在不破坏封装性的前提下,捕获和恢复对象的内部状态。这在许多应用中都非常有用,特别是在需要实现撤销、恢复或历史记录功能的情况下

using System;

// Originator
public class Originator
{
    public string State { get; set; }

    public Memento CreateMemento()
    {
        return new Memento(State);
    }

    public void RestoreMemento(Memento memento)
    {
        State = memento.State;
    }
}

// Memento
public class Memento
{
    public string State { get; }

    public Memento(string state)
    {
        State = state;
    }
}

// Caretaker
public class Caretaker
{
    public Memento Memento { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        Originator originator = new Originator();
        originator.State = "State 1";

        Caretaker caretaker = new Caretaker();
        caretaker.Memento = originator.CreateMemento();

        originator.State = "State 2";
        Console.WriteLine("Current state: " + originator.State);

        originator.RestoreMemento(caretaker.Memento);
        Console.WriteLine("Restored state: " + originator.State);
    }
}

14.桥接模式 (Bridge Pattern)

桥接模式的主要作用是解耦抽象部分和实现部分,使它们可以独立地变化。这使得在系统中可以轻松添加新的抽象部分或实现部分,而不需要修改现有代码

using System;

// Implementor
interface IMessageSender
{
    void SendMessage(string message);
}

// Concrete Implementors
class EmailSender : IMessageSender
{
    public void SendMessage(string message)
    {
        Console.WriteLine("Sending email: " + message);
    }
}

class SMSSender : IMessageSender
{
    public void SendMessage(string message)
    {
        Console.WriteLine("Sending SMS: " + message);
    }
}

// Abstraction
abstract class Message
{
    protected IMessageSender sender;

    public Message(IMessageSender sender)
    {
        this.sender = sender;
    }

    public abstract void Send();
}

// Concrete Abstractions
class ShortMessage : Message
{
    public ShortMessage(IMessageSender sender) : base(sender) { }

    public override void Send()
    {
        Console.WriteLine("Preparing a short message...");
        sender.SendMessage("This is a short message.");
    }
}

class LongEmail : Message
{
    public LongEmail(IMessageSender sender) : base(sender) { }

    public override void Send()
    {
        Console.WriteLine("Preparing a long email...");
        sender.SendMessage("This is a long email.");
    }
}

class Program
{
    static void Main(string[] args)
    {
        IMessageSender emailSender = new EmailSender();
        IMessageSender smsSender = new SMSSender();

        Message shortMessage = new ShortMessage(emailSender);
        Message longEmail = new LongEmail(smsSender);

        shortMessage.Send();
        longEmail.Send();
    }
}


15.组合模式 (Composite Pattern)

组合模式的主要作用是让客户端能够一致地对待单个对象和组合对象,从而简化了客户端代码。这对于处理树形结构数据非常有用,如图形界面中的控件布局、文件系统的文件夹和文件等。

using System;
using System.Collections.Generic;

// Component
abstract class Component
{
    protected string name;

    public Component(string name)
    {
        this.name = name;
    }

    public abstract void Display(int depth);
}

// Leaf
class Leaf : Component
{
    public Leaf(string name) : base(name) { }

    public override void Display(int depth)
    {
        Console.WriteLine(new string('-', depth) + name);
    }
}

// Composite
class Composite : Component
{
    private List<Component> children = new List<Component>();

    public Composite(string name) : base(name) { }

    public void Add(Component component)
    {
        children.Add(component);
    }

    public void Remove(Component component)
    {
        children.Remove(component);
    }

    public override void Display(int depth)
    {
        Console.WriteLine(new string('-', depth) + name);
        foreach (var child in children)
        {
            child.Display(depth + 2);
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Composite root = new Composite("Root");
        root.Add(new Leaf("Leaf 1"));
        root.Add(new Leaf("Leaf 2"));

        Composite composite = new Composite("Composite 1");
        composite.Add(new Leaf("Leaf 3"));
        composite.Add(new Leaf("Leaf 4"));

        root.Add(composite);

        root.Display(0);
    }
}

16.原型模式(Prototype Pattern)

它允许你复制对象而无需暴露其具体类。原型模式通常包括一个原型接口,具体的原型类以及一个原型管理器。客户端通过原型管理器来复制(克隆)原型对象。

using System;

// 原型接口
public interface IPrototype
{
    IPrototype Clone();
}

// 具体原型类
public class ConcretePrototype : IPrototype
{
    private int _data;

    public ConcretePrototype(int data)
    {
        _data = data;
    }

    public IPrototype Clone()
    {
        // 实现对象的浅拷贝
        return new ConcretePrototype(_data);
    }

    public void SetData(int data)
    {
        _data = data;
    }

    public int GetData()
    {
        return _data;
    }
}

// 原型管理器
public class PrototypeManager
{
    private IPrototype _prototype;

    public PrototypeManager(IPrototype prototype)
    {
        _prototype = prototype;
    }

    public IPrototype CreateCopy()
    {
        return _prototype.Clone();
    }
}

class Program
{
    static void Main(string[] args)
    {
        // 创建具体原型对象
        var prototype = new ConcretePrototype(10);

        // 创建原型管理器并设置原型对象
        var manager = new PrototypeManager(prototype);

        // 克隆原型对象
        var clonedPrototype = manager.CreateCopy() as ConcretePrototype;

        // 修改克隆对象的数据
        clonedPrototype.SetData(20);

        // 输出原型对象和克隆对象的数据
        Console.WriteLine("Original Prototype Data: " + prototype.GetData());
        Console.WriteLine("Cloned Prototype Data: " + clonedPrototype.GetData());
    }
}

17.外观模式 (Facade Pattern)

外观模式的主要目标是降低客户端与子系统之间的耦合度,同时提供一个更简单、更易用的接口,使客户端代码更加清晰和易于维护。这对于处理复杂系统或第三方库的使用非常有用,因为客户端可以通过外观接口访问这些系统,而不需要了解内部的复杂性。

using System;

// Subsystem 1
class Light
{
    public void TurnOn()
    {
        Console.WriteLine("Light is on");
    }

    public void TurnOff()
    {
        Console.WriteLine("Light is off");
    }
}

// Subsystem 2
class AirConditioner
{
    public void StartCooling()
    {
        Console.WriteLine("Air conditioner is cooling");
    }

    public void StopCooling()
    {
        Console.WriteLine("Air conditioner has stopped cooling");
    }
}

// Facade
class HomeAutomationFacade
{
    private Light light;
    private AirConditioner airConditioner;

    public HomeAutomationFacade()
    {
        light = new Light();
        airConditioner = new AirConditioner();
    }

    public void LeaveHome()
    {
        Console.WriteLine("Leaving home...");
        light.TurnOff();
        airConditioner.StopCooling();
    }

    public void ReturnHome()
    {
        Console.WriteLine("Returning home...");
        light.TurnOn();
        airConditioner.StartCooling();
    }
}

class Program
{
    static void Main(string[] args)
    {
        HomeAutomationFacade automation = new HomeAutomationFacade();

        // Leaving home
        automation.LeaveHome();

        // Returning home
        automation.ReturnHome();
    }
}

18.解释器模式(Interpreter Pattern)

解释器模式用于解释特定语言或规则的表达式。这个模式将一个语言的解释器实现为一个类层次结构,并使用该层次结构来解释表达式。通常,解释器模式适用于需要执行或解释特定语法规则的应用,如编程语言解释器、查询语言解释器等。

using System;

// 1. 抽象表达式
public abstract class Expression
{
    public abstract int Interpret(Context context);
}

// 2. 终结符表达式
public class NumberExpression : Expression
{
    private int number;

    public NumberExpression(int number)
    {
        this.number = number;
    }

    public override int Interpret(Context context)
    {
        return number;
    }
}

// 3. 非终结符表达式
public class AdditionExpression : Expression
{
    private Expression left;
    private Expression right;

    public AdditionExpression(Expression left, Expression right)
    {
        this.left = left;
        this.right = right;
    }

    public override int Interpret(Context context)
    {
        return left.Interpret(context) + right.Interpret(context);
    }
}

// 4. 上下文
public class Context
{
    // 存储解释器所需的数据
}

class Program
{
    static void Main()
    {
        // 构建解释器表达式:2 + 3
        Expression expression = new AdditionExpression(new NumberExpression(2), new NumberExpression(3));

        // 创建上下文
        Context context = new Context();

        // 使用解释器解释表达式
        int result = expression.Interpret(context);

        Console.WriteLine("2 + 3 = " + result);
    }
}

19.享元模式(Flyweight Pattern)

享元模式用于减少应用程序中对象的内存占用或计算成本,通过共享相似对象的内部状态来实现。享元模式通常用于需要大量相似对象的情况,以减少内存消耗。

using System;
using System.Collections.Generic;

// 1. 享元接口
public interface IShape
{
    void Draw(int x, int y);
}

// 2. 具体享元
public class Circle : IShape
{
    private string color;

    public Circle(string color)
    {
        this.color = color;
    }

    public void Draw(int x, int y)
    {
        Console.WriteLine($"Draw a {color} circle at ({x}, {y}).");
    }
}

// 3. 享元工厂
public class ShapeFactory
{
    private Dictionary<string, IShape> shapes = new Dictionary<string, IShape>();

    public IShape GetCircle(string color)
    {
        if (!shapes.ContainsKey(color))
        {
            shapes[color] = new Circle(color);
        }
        return shapes[color];
    }
}

class Program
{
    static void Main()
    {
        ShapeFactory factory = new ShapeFactory();

        IShape redCircle = factory.GetCircle("red");
        IShape greenCircle = factory.GetCircle("green");

        redCircle.Draw(10, 10);
        greenCircle.Draw(20, 20);

        // Non-shared flyweight
        IShape blueCircle = new Circle("blue");
        blueCircle.Draw(30, 30);
    }
}

20.中介者模式(Mediator Pattern)

中介者模式用于减少对象之间的直接通信,以减少耦合并促进松散耦合。中介者模式通过引入一个中介者对象来协调对象之间的通信,从而实现对象之间的解耦。

using System;

// 1. 中介者接口
public interface IMediator
{
    void SendMessage(Colleague colleague, string message);
}

// 2. 具体中介者
public class ConcreteMediator : IMediator
{
    public void SendMessage(Colleague colleague, string message)
    {
        Console.WriteLine($"Message from {colleague.Name}: {message}");
    }
}

// 3. 同事对象
public class Colleague
{
    public string Name { get; }

    private IMediator mediator;

    public Colleague(string name, IMediator mediator)
    {
        Name = name;
        this.mediator = mediator;
    }

    public void Send(string message)
    {
        Console.WriteLine($"{Name} sends message: {message}");
        mediator.SendMessage(this, message);
    }
}

class Program
{
    static void Main()
    {
        // 创建中介者
        IMediator mediator = new ConcreteMediator();

        // 创建同事对象
        Colleague colleague1 = new Colleague("Colleague 1", mediator);
        Colleague colleague2 = new Colleague("Colleague 2", mediator);

        // 同事对象之间通过中介者进行通信
        colleague1.Send("Hello, Colleague 2!");
        colleague2.Send("Hi, Colleague 1!");
    }
}

21.迭代器模式(Iterator Pattern)

迭代器模式提供一种方法来访问一个聚合对象中的每个元素,而无需暴露该对象的内部结构。迭代子模式将迭代行为封装在独立的迭代子对象中,从而使客户端可以遍历聚合对象而不需要知道其具体实现。

using System;
using System.Collections;
using System.Collections.Generic;

// 1. 迭代器接口
public interface IIterator<T>
{
    T Next();
    bool HasNext();
}

// 2. 具体迭代器
public class ConcreteIterator<T> : IIterator<T>
{
    private List<T> collection;
    private int position = 0;

    public ConcreteIterator(List<T> collection)
    {
        this.collection = collection;
    }

    public T Next()
    {
        if (HasNext())
        {
            T item = collection[position];
            position++;
            return item;
        }
        throw new InvalidOperationException("No more elements.");
    }

    public bool HasNext()
    {
        return position < collection.Count;
    }
}

// 3. 聚合对象接口
public interface IAggregate<T>
{
    IIterator<T> CreateIterator();
}

// 4. 具体聚合对象
public class ConcreteAggregate<T> : IAggregate<T>
{
    private List<T> items = new List<T>();

    public void AddItem(T item)
    {
        items.Add(item);
    }

    public IIterator<T> CreateIterator()
    {
        return new ConcreteIterator<T>(items);
    }
}

class Program
{
    static void Main()
    {
        ConcreteAggregate<string> aggregate = new ConcreteAggregate<string>();
        aggregate.AddItem("Item 1");
        aggregate.AddItem("Item 2");
        aggregate.AddItem("Item 3");

        IIterator<string> iterator = aggregate.CreateIterator();

        while (iterator.HasNext())
        {
            Console.WriteLine(iterator.Next());
        }
    }
}

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

抽象工厂提供了一种创建一组相关或依赖对象的方式,而无需指定其具体类。这个模式允许你创建对象家族,而不需要暴露其创建逻辑。

using System;

// 抽象工厂接口
public interface IAbstractFactory
{
    IAbstractProductA CreateProductA();
    IAbstractProductB CreateProductB();
}

// 具体工厂1
public class ConcreteFactory1 : IAbstractFactory
{
    public IAbstractProductA CreateProductA()
    {
        return new ConcreteProductA1();
    }

    public IAbstractProductB CreateProductB()
    {
        return new ConcreteProductB1();
    }
}

// 具体工厂2
public class ConcreteFactory2 : IAbstractFactory
{
    public IAbstractProductA CreateProductA()
    {
        return new ConcreteProductA2();
    }

    public IAbstractProductB CreateProductB()
    {
        return new ConcreteProductB2();
    }
}

// 抽象产品A
public interface IAbstractProductA
{
    string OperationA();
}

// 具体产品A1
public class ConcreteProductA1 : IAbstractProductA
{
    public string OperationA()
    {
        return "Product A1 operation";
    }
}

// 具体产品A2
public class ConcreteProductA2 : IAbstractProductA
{
    public string OperationA()
    {
        return "Product A2 operation";
    }
}

// 抽象产品B
public interface IAbstractProductB
{
    string OperationB();
}

// 具体产品B1
public class ConcreteProductB1 : IAbstractProductB
{
    public string OperationB()
    {
        return "Product B1 operation";
    }
}

// 具体产品B2
public class ConcreteProductB2 : IAbstractProductB
{
    public string OperationB()
    {
        return "Product B2 operation";
    }
}

// 客户端代码
class Program
{
    public static void ClientCode(IAbstractFactory factory)
    {
        var productA = factory.CreateProductA();
        var productB = factory.CreateProductB();

        Console.WriteLine(productA.OperationA());
        Console.WriteLine(productB.OperationB());
    }

    static void Main(string[] args)
    {
        // 使用具体工厂1
        var factory1 = new ConcreteFactory1();
        ClientCode(factory1);

        // 使用具体工厂2
        var factory2 = new ConcreteFactory2();
        ClientCode(factory2);
    }
}

23.建造者模式(Builder Pattern)

建造者模式是一种创建型设计模式,它允许你创建一个复杂对象的构建过程与该对象的表示分离。建造者模式通常包括一个指挥者(Director)、一个抽象建造者(Builder)、多个具体建造者(ConcreteBuilder),以及一个产品(Product)类。

using System;

// 产品类
class Product
{
    public string PartA { get; set; }
    public string PartB { get; set; }
    public string PartC { get; set; }

    public void Show()
    {
        Console.WriteLine($"Part A: {PartA}");
        Console.WriteLine($"Part B: {PartB}");
        Console.WriteLine($"Part C: {PartC}");
    }
}

// 抽象建造者
interface IBuilder
{
    void BuildPartA();
    void BuildPartB();
    void BuildPartC();
    Product GetResult();
}

// 具体建造者A
class ConcreteBuilderA : IBuilder
{
    private Product product = new Product();

    public void BuildPartA()
    {
        product.PartA = "Part A for ConcreteBuilderA";
    }

    public void BuildPartB()
    {
        product.PartB = "Part B for ConcreteBuilderA";
    }

    public void BuildPartC()
    {
        product.PartC = "Part C for ConcreteBuilderA";
    }

    public Product GetResult()
    {
        return product;
    }
}

// 具体建造者B
class ConcreteBuilderB : IBuilder
{
    private Product product = new Product();

    public void BuildPartA()
    {
        product.PartA = "Part A for ConcreteBuilderB";
    }

    public void BuildPartB()
    {
        product.PartB = "Part B for ConcreteBuilderB";
    }

    public void BuildPartC()
    {
        product.PartC = "Part C for ConcreteBuilderB";
    }

    public Product GetResult()
    {
        return product;
    }
}

// 指挥者
class Director
{
    public void Construct(IBuilder builder)
    {
        builder.BuildPartA();
        builder.BuildPartB();
        builder.BuildPartC();
    }
}

class Program
{
    static void Main(string[] args)
    {
        Director director = new Director();
        IBuilder builderA = new ConcreteBuilderA();
        IBuilder builderB = new ConcreteBuilderB();

        // 使用具体建造者A创建产品
        director.Construct(builderA);
        Product productA = builderA.GetResult();
        Console.WriteLine("Product from ConcreteBuilderA:");
        productA.Show();

        // 使用具体建造者B创建产品
        director.Construct(builderB);
        Product productB = builderB.GetResult();
        Console.WriteLine("Product from ConcreteBuilderB:");
        productB.Show();
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值