设计模式的简要分类与说明

创建型模式

单例模式

简单介绍:确保一个类只有一个实例,并提供一个全局访问点。就像 Windows 系统中的任务管理器,不管从系统的哪个地方打开它,都是同一个任务管理器。
伪代码

public class Singleton
{
    private static Singleton instance;

    private Singleton()
    {
        // 私有构造函数,防止外部实例化
    }

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

工厂模式

简单介绍:把创建对象的过程封装起来,就像一个工厂,你告诉它你想要什么产品,它就给你生产出来,使用者无需关心具体的创建过程。
伪代码

// 产品基类
public abstract class Product
{
    public abstract string Operation();
}

// 具体产品 A
public class ConcreteProductA : Product
{
    public override string Operation()
    {
        return "具体产品 A 的操作";
    }
}

// 具体产品 B
public class ConcreteProductB : Product
{
    public override string Operation()
    {
        return "具体产品 B 的操作";
    }
}

// 工厂类
public class Factory
{
    public static Product CreateProduct(string productType)
    {
        switch (productType)
        {
            case "A":
                return new ConcreteProductA();
            case "B":
                return new ConcreteProductB();
            default:
                return null;
        }
    }
}

抽象工厂模式

简单介绍:能生产一系列相关的产品,如同一个超级工厂,不仅能生产玩具汽车,还能生产配套的玩具小人、玩具加油站等。
伪代码

// 抽象产品 A
public abstract class AbstractProductA
{
    public abstract string OperationA();
}

// 抽象产品 B
public abstract class AbstractProductB
{
    public abstract string OperationB();
}

// 具体产品 A1
public class ConcreteProductA1 : AbstractProductA
{
    public override string OperationA()
    {
        return "具体产品 A1 的操作";
    }
}

// 具体产品 B1
public class ConcreteProductB1 : AbstractProductB
{
    public override string OperationB()
    {
        return "具体产品 B1 的操作";
    }
}

// 具体产品 A2
public class ConcreteProductA2 : AbstractProductA
{
    public override string OperationA()
    {
        return "具体产品 A2 的操作";
    }
}

// 具体产品 B2
public class ConcreteProductB2 : AbstractProductB
{
    public override string OperationB()
    {
        return "具体产品 B2 的操作";
    }
}

// 抽象工厂
public abstract class AbstractFactory
{
    public abstract AbstractProductA CreateProductA();
    public abstract AbstractProductB CreateProductB();
}

// 具体工厂 1
public class ConcreteFactory1 : AbstractFactory
{
    public override AbstractProductA CreateProductA()
    {
        return new ConcreteProductA1();
    }

    public override AbstractProductB CreateProductB()
    {
        return new ConcreteProductB1();
    }
}

// 具体工厂 2
public class ConcreteFactory2 : AbstractFactory
{
    public override AbstractProductA CreateProductA()
    {
        return new ConcreteProductA2();
    }

    public override AbstractProductB CreateProductB()
    {
        return new ConcreteProductB2();
    }
}

建造者模式

简单介绍:把一个复杂对象的创建过程分解成多个简单的步骤,就像建房子,有不同的工人负责不同部分,最后组合成完整的房子。
伪代码

// 产品类
public class Product
{
    private List<string> parts = new List<string>();

    public void AddPart(string part)
    {
        parts.Add(part);
    }

    public void Show()
    {
        Console.WriteLine("产品部件:");
        foreach (var part in parts)
        {
            Console.WriteLine(part);
        }
    }
}

// 抽象建造者
public abstract class Builder
{
    public abstract void BuildPartA();
    public abstract void BuildPartB();
    public abstract Product GetResult();
}

// 具体建造者
public class ConcreteBuilder : Builder
{
    private Product product = new Product();

    public override void BuildPartA()
    {
        product.AddPart("部件 A");
    }

    public override void BuildPartB()
    {
        product.AddPart("部件 B");
    }

    public override Product GetResult()
    {
        return product;
    }
}

// 指挥者
public class Director
{
    public Product Construct(Builder builder)
    {
        builder.BuildPartA();
        builder.BuildPartB();
        return builder.GetResult();
    }
}

原型模式

简单介绍:根据一个已经存在的对象,快速创建出和它一样的新对象,类似用复印机复印东西。
伪代码

using System;

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

// 具体原型
public class ConcretePrototype : IPrototype
{
    public string Value { get; set; }

    public ConcretePrototype(string value)
    {
        Value = value;
    }

    public IPrototype Clone()
    {
        return new ConcretePrototype(this.Value);
    }

    public override string ToString()
    {
        return $"ConcretePrototype: {Value}";
    }
}

结构型模式

代理模式

简单介绍:用一个代理对象来代替真实对象,控制对真实对象的访问,比如通过经纪人联系明星,经纪人就是代理。
伪代码

// 真实主题
public class RealSubject
{
    public string Request()
    {
        return "真实主题的请求";
    }
}

// 代理
public class Proxy
{
    private RealSubject realSubject;

    public Proxy()
    {
        realSubject = new RealSubject();
    }

    public string Request()
    {
        // 可以在调用真实主题前或后添加额外逻辑
        Console.WriteLine("代理预处理");
        string result = realSubject.Request();
        Console.WriteLine("代理后处理");
        return result;
    }
}

适配器模式

简单介绍:把一个类的接口转换成另一个接口,使原本不兼容的接口可以协同工作,类似用转换插头连接不同标准的电器。
伪代码

// 适配者
public class Adaptee
{
    public string SpecificRequest()
    {
        return "适配者的特定请求";
    }
}

// 目标接口
public interface Target
{
    string Request();
}

// 适配器
public class Adapter : Target
{
    private Adaptee adaptee;

    public Adapter()
    {
        adaptee = new Adaptee();
    }

    public string Request()
    {
        return adaptee.SpecificRequest();
    }
}

桥接模式

简单介绍:将两个有联系但可独立变化的部分分离,使它们能独立变化又能协同工作,如手机的软件和硬件通过接口联系且可各自升级。
伪代码

// 实现者接口
public interface Implementor
{
    string OperationImplementation();
}

// 具体实现者 A
public class ConcreteImplementorA : Implementor
{
    public string OperationImplementation()
    {
        return "具体实现 A 的操作";
    }
}

// 具体实现者 B
public class ConcreteImplementorB : Implementor
{
    public string OperationImplementation()
    {
        return "具体实现 B 的操作";
    }
}

// 抽象类
public abstract class Abstraction
{
    protected Implementor implementor;

    public Abstraction(Implementor implementor)
    {
        this.implementor = implementor;
    }

    public virtual string Operation()
    {
        return implementor.OperationImplementation();
    }
}

// 细化抽象类
public class RefinedAbstraction : Abstraction
{
    public RefinedAbstraction(Implementor implementor) : base(implementor)
    {
    }

    public override string Operation()
    {
        string baseResult = base.Operation();
        return $"细化抽象操作,包含:{baseResult}";
    }
}

装饰器模式

简单介绍:在不改变原来对象的基础上,给对象添加额外功能,比如给蛋糕添加水果和巧克力装饰。
伪代码

// 组件接口
public interface Component
{
    string Operation();
}

// 具体组件
public class ConcreteComponent : Component
{
    public string Operation()
    {
        return "具体组件的操作";
    }
}

// 装饰器抽象类
public abstract class Decorator : Component
{
    protected Component component;

    public Decorator(Component component)
    {
        this.component = component;
    }

    public virtual string Operation()
    {
        return component.Operation();
    }
}

// 具体装饰器 A
public class ConcreteDecoratorA : Decorator
{
    public ConcreteDecoratorA(Component component) : base(component)
    {
    }

    public override string Operation()
    {
        return $"装饰 A 前 {base.Operation()} 装饰 A 后";
    }
}

// 具体装饰器 B
public class ConcreteDecoratorB : Decorator
{
    public ConcreteDecoratorB(Component component) : base(component)
    {
    }

    public override string Operation()
    {
        return $"装饰 B 前 {base.Operation()} 装饰 B 后";
    }
}

外观模式

简单介绍:把复杂的系统封装起来,提供一个简单统一的接口给用户,如按电脑开机键,无需了解内部硬件和软件的复杂工作。
伪代码

// 子系统 1
public class Subsystem1
{
    public string Operation1()
    {
        return "子系统 1 的操作";
    }
}

// 子系统 2
public class Subsystem2
{
    public string Operation2()
    {
        return "子系统 2 的操作";
    }
}

// 外观类
public class Facade
{
    private Subsystem1 subsystem1;
    private Subsystem2 subsystem2;

    public Facade()
    {
        subsystem1 = new Subsystem1();
        subsystem2 = new Subsystem2();
    }

    public string Operation()
    {
        string result = subsystem1.Operation1();
        result += subsystem2.Operation2();
        return result;
    }
}

享元模式

简单介绍:共享相同的对象以节省内存空间,像围棋棋盘上众多相同的黑子和白子可共享使用。
伪代码

using System.Collections.Generic;

// 享元类
public class Flyweight
{
    private string sharedState;

    public Flyweight(string sharedState)
    {
        this.sharedState = sharedState;
    }

    public string Operation(string extrinsicState)
    {
        return $"共享状态: {sharedState}, 外部状态: {extrinsicState}";
    }
}

// 享元工厂
public class FlyweightFactory
{
    private Dictionary<string, Flyweight> flyweights = new Dictionary<string, Flyweight>();

    public Flyweight GetFlyweight(string sharedState)
    {
        if (!flyweights.ContainsKey(sharedState))
        {
            flyweights[sharedState] = new Flyweight(sharedState);
        }
        return flyweights[sharedState];
    }
}

组合模式

简单介绍:将单个对象和组合对象统一管理,方便操作,如公司里部门经理和普通员工可统一管理。
伪代码

using System.Collections.Generic;

// 组件抽象类
public abstract class Component
{
    public abstract string Operation();
    public virtual void Add(Component component) { }
    public virtual void Remove(Component component) { }
    public virtual Component GetChild(int index) { return null; }
}

// 叶子节点
public class Leaf : Component
{
    public override string Operation()
    {
        return "叶子节点的操作";
    }
}

// 组合节点
public class Composite : Component
{
    private List<Component> children = new List<Component>();

    public override string Operation()
    {
        string result = "组合节点操作,包含子节点操作:";
        foreach (var child in children)
        {
            result += child.Operation();
        }
        return result;
    }

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

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

    public override Component GetChild(int index)
    {
        return children[index];
    }
}

行为型模式

策略模式

简单介绍:把不同的算法或行为封装成不同策略,可根据需要选择,如去一个地方可选择走路、骑车或坐公交等不同方式。
伪代码

// 策略接口
public interface Strategy
{
    string Execute();
}

// 具体策略 A
public class ConcreteStrategyA : Strategy
{
    public string Execute()
    {
        return "具体策略 A 的执行";
    }
}

// 具体策略 B
public class ConcreteStrategyB : Strategy
{
    public string Execute()
    {
        return "具体策略 B 的执行";
    }
}

// 上下文
public class Context
{
    private Strategy strategy;

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

    public string ExecuteStrategy()
    {
        return strategy.Execute();
    }
}

模板方法模式

简单介绍:定义一个操作的算法骨架,将一些步骤延迟到子类实现,如做蛋糕有基本流程,但不同口味蛋糕在材料和烘焙时间上细节不同。
伪代码

// 抽象类
public abstract class AbstractClass
{
    public void TemplateMethod()
    {
        BaseOperation1();
        RequiredOperations();
        BaseOperation2();
    }

    protected void BaseOperation1()
    {
        Console.WriteLine("抽象类的基本操作 1");
    }

    protected void BaseOperation2()
    {
        Console.WriteLine("抽象类的基本操作 2");
    }

    protected abstract void RequiredOperations();
}

// 具体类
public class ConcreteClass : AbstractClass
{
    protected override void RequiredOperations()
    {
        Console.WriteLine("具体类的必要操作");
    }
}

观察者模式

简单介绍:当一个对象状态变化时,通知依赖它的其他对象,如明星发动态,关注他的粉丝会收到通知。
伪代码

using System.Collections.Generic;

// 主题接口
public interface ISubject
{
    void Attach(IObserver observer);
    void Detach(IObserver observer);
    void Notify();
}

// 观察者接口
public interface IObserver
{
    void Update();
}

// 具体主题
public class Subject : ISubject
{
    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();
        }
    }
}

// 具体观察者
public class ConcreteObserver : IObserver
{
    public void Update()
    {
        Console.WriteLine("具体观察者收到通知");
    }
}

迭代器模式

简单介绍:提供一种顺序访问集合对象元素的方法,且不暴露集合内部结构,如遍历书架上的书。
伪代码

using System.Collections.Generic;

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

// 集合接口
public interface Aggregate<T>
{
    Iterator<T> CreateIterator();
}

// 具体集合
public class ConcreteAggregate<T> : Aggregate<T>
{
    private List<T> items = new List<T>();

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

    public Iterator<T> CreateIterator()
    {
        return new ConcreteIterator<T>(this);
    }

    public int Count
    {
        get { return items.Count; }
    }

    public T GetItem(int index)
    {
        return items[index];
    }
}

// 具体迭代器
public class ConcreteIterator<T> : Iterator<T>
{
    private ConcreteAggregate<T> aggregate;
    private int position = 0;

	public ConcreteIterator(ConcreteAggregate<T> aggregate)
    {
        this.aggregate = aggregate;
    }

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

    public T Next()
    {
        if (HasNext())
        {
            return aggregate.GetItem(position++);
        }
        return default(T);
    }
}

责任链模式

简单介绍:多个对象都有机会处理请求,请求在对象链上传递,直到有对象处理它,如公司请假依次找组长、经理、老板审批。
伪代码

// 处理者抽象类
public abstract class Handler
{
    protected Handler successor;

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

    public abstract string HandleRequest(string request);
}

// 具体处理者 A
public class ConcreteHandlerA : Handler
{
    public override string HandleRequest(string request)
    {
        if (request == "A请求")
        {
            return "ConcreteHandlerA 处理请求";
        }
        if (successor != null)
        {
            return successor.HandleRequest(request);
        }
        return "无人处理请求";
    }
}

// 具体处理者 B
public class ConcreteHandlerB : Handler
{
    public override string HandleRequest(string request)
    {
        if (request == "B请求")
        {
            return "ConcreteHandlerB 处理请求";
        }
        if (successor != null)
        {
            return successor.HandleRequest(request);
        }
        return "无人处理请求";
    }
}

命令模式

简单介绍:把请求封装成命令对象,方便对请求进行处理、撤销等操作,如用遥控器按不同按钮控制电视执行不同操作。
伪代码

// 接收者
public class Receiver
{
    public string Action()
    {
        return "接收者执行动作";
    }
}

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

// 具体命令
public class ConcreteCommand : ICommand
{
    private Receiver receiver;

    public ConcreteCommand(Receiver receiver)
    {
        this.receiver = receiver;
    }

    public string Execute()
    {
        return receiver.Action();
    }
}

// 调用者
public class Invoker
{
    private ICommand command;

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

    public string ExecuteCommand()
    {
        if (command != null)
        {
            return command.Execute();
        }
        return "无命令可执行";
    }
}

备忘录模式

简单介绍:保存对象状态,以便在需要时恢复到之前状态,如编辑文档时保存版本,可回退到之前版本。
伪代码

// 备忘录类
public class Memento
{
    private string state;

    public Memento(string state)
    {
        this.state = state;
    }

    public string GetState()
    {
        return state;
    }
}

// 原发器
public class Originator
{
    private string state;

    public void SetState(string state)
    {
        this.state = state;
    }

    public string GetState()
    {
        return state;
    }

    public Memento SaveStateToMemento()
    {
        return new Memento(state);
    }

    public void GetStateFromMemento(Memento memento)
    {
        state = memento.GetState();
    }
}

// 管理者
public class Caretaker
{
    private Memento memento;

    public void SaveMemento(Memento memento)
    {
        this.memento = memento;
    }

    public Memento GetMemento()
    {
        return memento;
    }
}

状态模式

简单介绍:根据对象的不同状态执行不同操作,如手机在开机、关机、待机等不同状态下按同一按钮反应不同。
伪代码

// 状态接口
public interface IState
{
    string Handle();
}

// 具体状态 A
public class ConcreteStateA : IState
{
    public string Handle()
    {
        return "处于状态 A 的处理";
    }
}

// 具体状态 B
public class ConcreteStateB : IState
{
    public string Handle()
    {
        return "处于状态 B 的处理";
    }
}

// 上下文
public class Context
{
    private IState state;

    public Context(IState state)
    {
        this.state = state;
    }

    public void Request()
    {
        Console.WriteLine(state.Handle());
    }

    public void ChangeState(IState state)
    {
        this.state = state;
    }
}

访问者模式

简单介绍:把对不同对象的操作封装在访问者类中,方便对不同对象进行不同操作,如游客在动物园对不同动物做不同操作。
伪代码

// 元素接口
public interface IElement
{
    void Accept(IVisitor visitor);
}

// 具体元素 A
public class ConcreteElementA : IElement
{
    public void Accept(IVisitor visitor)
    {
        visitor.VisitConcreteElementA(this);
    }

    public string OperationA()
    {
        return "具体元素 A 的操作";
    }
}

// 具体元素 B
public class ConcreteElementB : IElement
{
    public void Accept(IVisitor visitor)
    {
        visitor.VisitConcreteElementB(this);
    }

    public string OperationB()
    {
        return "具体元素 B 的操作";
    }
}

// 访问者接口
public interface IVisitor
{
    void VisitConcreteElementA(ConcreteElementA element);
    void VisitConcreteElementB(ConcreteElementB element);
}

// 具体访问者
public class ConcreteVisitor : IVisitor
{
    public void VisitConcreteElementA(ConcreteElementA element)
    {
        Console.WriteLine($"访问者访问具体元素 A,执行:{element.OperationA()}");
    }

    public void VisitConcreteElementB(ConcreteElementB element)
    {
        Console.WriteLine($"访问者访问具体元素 B,执行:{element.OperationB()}");
    }
}

中介者模式

简单介绍:用中介对象封装对象之间的交互,降低对象间耦合度,如聊天室里大家通过服务器中介传递消息。
伪代码

// 中介者接口
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);
}

// 具体中介者
public class ConcreteMediator : IMediator
{
    public ConcreteColleagueA ColleagueA { get; set; }
    public ConcreteColleagueB ColleagueB { get; set; }

    public void Send(string message, Colleague colleague)
    {
        if (colleague == ColleagueA)
        {
            ColleagueB.Receive(message);
        }
        else
        {
            ColleagueA.Receive(message);
        }
    }
}

// 具体同事 A
public class ConcreteColleagueA : Colleague
{
    public ConcreteColleagueA(IMediator mediator) : base(mediator)
    {
    }

    public override void Send(string message)
    {
        mediator.Send(message, this);
    }

    public override void Receive(string message)
    {
        Console.WriteLine($"同事 A 收到消息:{message}");
    }
}

// 具体同事 B
public class ConcreteColleagueB : Colleague
{
    public ConcreteColleagueB(IMediator mediator) : base(mediator)
    {
    }

    public override void Send(string message)
    {
        mediator.Send(message, this);
    }

    public override void Receive(string message)
    {
        Console.WriteLine($"同事 B 收到消息:{message}");
    }
}

解释器模式

简单介绍:定义一个语言的文法,并且建立一个解释器来解释该语言中的句子,比如对数学表达式进行解析和计算。
伪代码

using System.Collections.Generic;

// 上下文类
public class Context
{
    private Dictionary<string, int> variables = new Dictionary<string, int>();

    public void SetVariable(string name, int value)
    {
        variables[name] = value;
    }

    public int GetVariable(string name)
    {
        return variables.ContainsKey(name) ? variables[name] : 0;
    }
}

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

// 终结符表达式
public class TerminalExpression : AbstractExpression
{
    private string variable;

    public TerminalExpression(string variable)
    {
        this.variable = variable;
    }

    public override int Interpret(Context context)
    {
        return context.GetVariable(variable);
    }
}

// 非终结符表达式(加法)
public class AddExpression : AbstractExpression
{
    private AbstractExpression left;
    private AbstractExpression right;

    public AddExpression(AbstractExpression left, AbstractExpression right)
    {
        this.left = left;
        this.right = right;
    }

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

posted on 2025-01-28 16:12  HutatsuiwaKaede  阅读(2)  评论(0编辑  收藏  举报

导航