C++ 设计模式详尽教程

设计模式是软件设计中常见问题的典型解决方案,它们是可以重复使用的设计模板。本教程将详细介绍23种经典设计模式在C++中的实现和应用。

一、设计模式概述

1.1 设计模式分类

设计模式通常分为三大类:

  1. 创建型模式:处理对象创建机制
  2. 结构型模式:处理类和对象的组合
  3. 行为型模式:处理对象间的通信和职责分配

1.2 设计模式六大原则

  1. 开闭原则:对扩展开放,对修改关闭
  2. 单一职责原则:一个类只负责一个功能领域
  3. 里氏替换原则:子类可以扩展父类功能但不能改变原有功能
  4. 依赖倒置原则:依赖于抽象而非具体实现
  5. 接口隔离原则:使用多个专用接口比使用单一总接口好
  6. 迪米特法则:一个对象应尽可能少了解其他对象

二、创建型模式

2.1 单例模式 (Singleton)

意图:保证一个类仅有一个实例,并提供一个全局访问点。

class Singleton {
private:
    static Singleton* instance;
    Singleton() {}  // 私有构造函数

public:
    static Singleton* getInstance() {
        if (instance == nullptr) {
            instance = new Singleton();
        }
        return instance;
    }

    // 删除拷贝构造函数和赋值操作符
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;
};
// 初始化静态成员
Singleton* Singleton::instance = nullptr;

线程安全版本

#include <mutex>
class Singleton {
private:
    static Singleton* instance;
    static std::mutex mtx;
    Singleton() {}

public:
    static Singleton* getInstance() {
        std::lock_guard<std::mutex> lock(mtx);
        if (instance == nullptr) {
            instance = new Singleton();
        }
        return instance;
    }

    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;
};
Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mtx;

2.2 工厂方法模式 (Factory Method)

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

// 抽象产品
class Product {
public:
    virtual ~Product() {}
    virtual void operation() = 0;
};
// 具体产品A
class ConcreteProductA : public Product {
public:
    void operation() override {
        std::cout << "ConcreteProductA operation" << std::endl;
    }
};
// 具体产品B
class ConcreteProductB : public Product {
public:
    void operation() override {
        std::cout << "ConcreteProductB operation" << std::endl;
    }
};
// 抽象工厂
class Creator {
public:
    virtual ~Creator() {}
    virtual Product* createProduct() = 0;

    void someOperation() {
        Product* product = createProduct();
        product->operation();
        delete product;
    }
};
// 具体工厂A
class ConcreteCreatorA : public Creator {
public:
    Product* createProduct() override {
        return new ConcreteProductA();
    }
};
// 具体工厂B
class ConcreteCreatorB : public Creator {
public:
    Product* createProduct() override {
        return new ConcreteProductB();
    }
};

2.3 抽象工厂模式 (Abstract Factory)

意图:提供一个创建一系列相关或依赖对象的接口,而无需指定它们具体的类。

// 抽象产品A
class AbstractProductA {
public:
    virtual ~AbstractProductA() {}
    virtual void operationA() = 0;
};
// 具体产品A1
class ProductA1 : public AbstractProductA {
public:
    void operationA() override {
        std::cout << "ProductA1 operation" << std::endl;
    }
};
// 具体产品A2
class ProductA2 : public AbstractProductA {
public:
    void operationA() override {
        std::cout << "ProductA2 operation" << std::endl;
    }
};
// 抽象产品B
class AbstractProductB {
public:
    virtual ~AbstractProductB() {}
    virtual void operationB() = 0;
};
// 具体产品B1
class ProductB1 : public AbstractProductB {
public:
    void operationB() override {
        std::cout << "ProductB1 operation" << std::endl;
    }
};
// 具体产品B2
class ProductB2 : public AbstractProductB {
public:
    void operationB() override {
        std::cout << "ProductB2 operation" << std::endl;
    }
};
// 抽象工厂
class AbstractFactory {
public:
    virtual ~AbstractFactory() {}
    virtual AbstractProductA* createProductA() = 0;
    virtual AbstractProductB* createProductB() = 0;
};
// 具体工厂1
class ConcreteFactory1 : public AbstractFactory {
public:
    AbstractProductA* createProductA() override {
        return new ProductA1();
    }

    AbstractProductB* createProductB() override {
        return new ProductB1();
    }
};
// 具体工厂2
class ConcreteFactory2 : public AbstractFactory {
public:
    AbstractProductA* createProductA() override {
        return new ProductA2();
    }

    AbstractProductB* createProductB() override {
        return new ProductB2();
    }
};

2.4 建造者模式 (Builder)

意图:将一个复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示。

// 产品类
class Product {
private:
    std::string partA;
    std::string partB;
    std::string partC;

public:
    void setPartA(const std::string& part) {
        partA = part;
    }

    void setPartB(const std::string& part) {
        partB = part;
    }

    void setPartC(const std::string& part) {
        partC = part;
    }

    void show() const {
        std::cout << "Product parts: " << partA << ", " << partB << ", " << partC << std::endl;
    }
};
// 抽象建造者
class Builder {
public:
    virtual ~Builder() {}
    virtual void buildPartA() = 0;
    virtual void buildPartB() = 0;
    virtual void buildPartC() = 0;
    virtual Product* getResult() = 0;
};
// 具体建造者
class ConcreteBuilder : public Builder {
private:
    Product* product;

public:
    ConcreteBuilder() : product(new Product()) {}

    ~ConcreteBuilder() {
        delete product;
    }

    void buildPartA() override {
        product->setPartA("PartA");
    }

    void buildPartB() override {
        product->setPartB("PartB");
    }

    void buildPartC() override {
        product->setPartC("PartC");
    }

    Product* getResult() override {
        return product;
    }
};
// 指挥者
class Director {
public:
    void construct(Builder* builder) {
        builder->buildPartA();
        builder->buildPartB();
        builder->buildPartC();
    }
};

2.5 原型模式 (Prototype)

意图:用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。

#include <iostream>
#include <string>
// 抽象原型类
class Prototype {
public:
    virtual ~Prototype() {}
    virtual Prototype* clone() const = 0;
    virtual void print() const = 0;
};
// 具体原型类
class ConcretePrototype : public Prototype {
private:
    std::string data;

public:
    ConcretePrototype(const std::string& d) : data(d) {}

    ConcretePrototype(const ConcretePrototype& other) : data(other.data) {
        std::cout << "ConcretePrototype copied" << std::endl;
    }

    Prototype* clone() const override {
        return new ConcretePrototype(*this);
    }

    void print() const override {
        std::cout << "Data: " << data << std::endl;
    }
};

三、结构型模式

3.1 适配器模式 (Adapter)

意图:将一个类的接口转换成客户希望的另外一个接口。

// 目标接口
class Target {
public:
    virtual ~Target() {}
    virtual void request() = 0;
};
// 需要适配的类
class Adaptee {
public:
    void specificRequest() {
        std::cout << "Adaptee's specific request" << std::endl;
    }
};
// 类适配器 (通过多重继承)
class ClassAdapter : public Target, private Adaptee {
public:
    void request() override {
        specificRequest();
    }
};
// 对象适配器 (通过组合)
class ObjectAdapter : public Target {
private:
    Adaptee* adaptee;

public:
    ObjectAdapter(Adaptee* a) : adaptee(a) {}

    void request() override {
        adaptee->specificRequest();
    }
};

3.2 桥接模式 (Bridge)

意图:将抽象部分与它的实现部分分离,使它们都可以独立地变化。

// 实现接口
class Implementor {
public:
    virtual ~Implementor() {}
    virtual void operationImpl() = 0;
};
// 具体实现A
class ConcreteImplementorA : public Implementor {
public:
    void operationImpl() override {
        std::cout << "ConcreteImplementorA operation" << std::endl;
    }
};
// 具体实现B
class ConcreteImplementorB : public Implementor {
public:
    void operationImpl() override {
        std::cout << "ConcreteImplementorB operation" << std::endl;
    }
};
// 抽象类
class Abstraction {
protected:
    Implementor* implementor;

public:
    Abstraction(Implementor* impl) : implementor(impl) {}
    virtual ~Abstraction() {}

    virtual void operation() {
        implementor->operationImpl();
    }
};
// 扩展抽象类
class RefinedAbstraction : public Abstraction {
public:
    RefinedAbstraction(Implementor* impl) : Abstraction(impl) {}

    void operation() override {
        std::cout << "Refined ";
        implementor->operationImpl();
    }
};

3.3 组合模式 (Composite)

意图:将对象组合成树形结构以表示"部分-整体"的层次结构。

#include <vector>
#include <memory>
// 组件接口
class Component {
public:
    virtual ~Component() {}
    virtual void operation() = 0;
    virtual void add(std::shared_ptr<Component> component) {}
    virtual void remove(std::shared_ptr<Component> component) {}
    virtual std::shared_ptr<Component> getChild(int index) { return nullptr; }
};
// 叶子节点
class Leaf : public Component {
public:
    void operation() override {
        std::cout << "Leaf operation" << std::endl;
    }
};
// 复合节点
class Composite : public Component {
private:
    std::vector<std::shared_ptr<Component>> children;

public:
    void operation() override {
        std::cout << "Composite operation" << std::endl;
        for (auto& child : children) {
            child->operation();
        }
    }

    void add(std::shared_ptr<Component> component) override {
        children.push_back(component);
    }

    void remove(std::shared_ptr<Component> component) override {
        children.erase(std::remove(children.begin(), children.end(), component), children.end());
    }

    std::shared_ptr<Component> getChild(int index) override {
        if (index >= 0 && index < children.size()) {
            return children[index];
        }
        return nullptr;
    }
};

3.4 装饰器模式 (Decorator)

意图:动态地给一个对象添加一些额外的职责。

// 组件接口
class Component {
public:
    virtual ~Component() {}
    virtual void operation() = 0;
};
// 具体组件
class ConcreteComponent : public Component {
public:
    void operation() override {
        std::cout << "ConcreteComponent operation" << std::endl;
    }
};
// 抽象装饰器
class Decorator : public Component {
protected:
    Component* component;

public:
    Decorator(Component* c) : component(c) {}

    void operation() override {
        if (component) {
            component->operation();
        }
    }
};
// 具体装饰器A
class ConcreteDecoratorA : public Decorator {
public:
    ConcreteDecoratorA(Component* c) : Decorator(c) {}

    void operation() override {
        Decorator::operation();
        addedBehavior();
    }

    void addedBehavior() {
        std::cout << "Added behavior from ConcreteDecoratorA" << std::endl;
    }
};
// 具体装饰器B
class ConcreteDecoratorB : public Decorator {
public:
    ConcreteDecoratorB(Component* c) : Decorator(c) {}

    void operation() override {
        Decorator::operation();
        addedBehavior();
    }

    void addedBehavior() {
        std::cout << "Added behavior from ConcreteDecoratorB" << std::endl;
    }
};

3.5 外观模式 (Facade)

意图:为子系统中的一组接口提供一个一致的界面。

// 子系统A
class SubsystemA {
public:
    void operationA() {
        std::cout << "SubsystemA operation" << std::endl;
    }
};
// 子系统B
class SubsystemB {
public:
    void operationB() {
        std::cout << "SubsystemB operation" << std::endl;
    }
};
// 子系统C
class SubsystemC {
public:
    void operationC() {
        std::cout << "SubsystemC operation" << std::endl;
    }
};
// 外观类
class Facade {
private:
    SubsystemA* subsystemA;
    SubsystemB* subsystemB;
    SubsystemC* subsystemC;

public:
    Facade() : subsystemA(new SubsystemA()), 
               subsystemB(new SubsystemB()), 
               subsystemC(new SubsystemC()) {}

    ~Facade() {
        delete subsystemA;
        delete subsystemB;
        delete subsystemC;
    }

    void operation1() {
        subsystemA->operationA();
        subsystemB->operationB();
    }

    void operation2() {
        subsystemB->operationB();
        subsystemC->operationC();
    }
};

3.6 享元模式 (Flyweight)

意图:运用共享技术有效地支持大量细粒度的对象。

#include <unordered_map>
#include <string>
// 享元接口
class Flyweight {
public:
    virtual ~Flyweight() {}
    virtual void operation(const std::string& extrinsicState) = 0;
};
// 具体享元
class ConcreteFlyweight : public Flyweight {
private:
    std::string intrinsicState;

public:
    ConcreteFlyweight(const std::string& state) : intrinsicState(state) {}

    void operation(const std::string& extrinsicState) override {
        std::cout << "Intrinsic State = " << intrinsicState 
                  << ", Extrinsic State = " << extrinsicState << std::endl;
    }
};
// 享元工厂
class FlyweightFactory {
private:
    std::unordered_map<std::string, Flyweight*> flyweights;

    std::string getKey(const std::string& state) {
        return state;
    }

public:
    ~FlyweightFactory() {
        for (auto& pair : flyweights) {
            delete pair.second;
        }
    }

    Flyweight* getFlyweight(const std::string& sharedState) {
        std::string key = getKey(sharedState);
        if (flyweights.find(key) == flyweights.end()) {
            flyweights[key] = new ConcreteFlyweight(sharedState);
        }
        return flyweights[key];
    }
};

3.7 代理模式 (Proxy)

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

// 抽象主题
class Subject {
public:
    virtual ~Subject() {}
    virtual void request() = 0;
};
// 真实主题
class RealSubject : public Subject {
public:
    void request() override {
        std::cout << "RealSubject request" << std::endl;
    }
};
// 代理
class Proxy : public Subject {
private:
    RealSubject* realSubject;

    bool checkAccess() {
        std::cout << "Proxy: Checking access prior to firing a real request" << std::endl;
        return true;
    }

    void logAccess() {
        std::cout << "Proxy: Logging the time of request" << std::endl;
    }

public:
    Proxy(RealSubject* subject) : realSubject(subject) {}

    ~Proxy() {
        delete realSubject;
    }

    void request() override {
        if (checkAccess()) {
            realSubject->request();
            logAccess();
        }
    }
};

四、行为型模式

4.1 责任链模式 (Chain of Responsibility)

意图:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。

#include <iostream>
// 处理器接口
class Handler {
protected:
    Handler* nextHandler;

public:
    Handler() : nextHandler(nullptr) {}
    virtual ~Handler() {}

    void setNext(Handler* handler) {
        nextHandler = handler;
    }

    virtual void handleRequest(int request) = 0;
};
// 具体处理器A
class ConcreteHandlerA : public Handler {
public:
    void handleRequest(int request) override {
        if (request < 10) {
            std::cout << "ConcreteHandlerA handled request " << request << std::endl;
        } else if (nextHandler) {
            nextHandler->handleRequest(request);
        } else {
            std::cout << "No handler for request " << request << std::endl;
        }
    }
};
// 具体处理器B
class ConcreteHandlerB : public Handler {
public:
    void handleRequest(int request) override {
        if (request >= 10 && request < 20) {
            std::cout << "ConcreteHandlerB handled request " << request << std::endl;
        } else if (nextHandler) {
            nextHandler->handleRequest(request);
        } else {
            std::cout << "No handler for request " << request << std::endl;
        }
    }
};
// 具体处理器C
class ConcreteHandlerC : public Handler {
public:
    void handleRequest(int request) override {
        if (request >= 20) {
            std::cout << "ConcreteHandlerC handled request " << request << std::endl;
        } else if (nextHandler) {
            nextHandler->handleRequest(request);
        } else {
            std::cout << "No handler for request " << request << std::endl;
        }
    }
};

4.2 命令模式 (Command)

意图:将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化。

#include <iostream>
#include <vector>
// 接收者
class Receiver {
public:
    void action() {
        std::cout << "Receiver action" << std::endl;
    }
};
// 命令接口
class Command {
public:
    virtual ~Command() {}
    virtual void execute() = 0;
};
// 具体命令
class ConcreteCommand : public Command {
private:
    Receiver* receiver;

public:
    ConcreteCommand(Receiver* r) : receiver(r) {}

    void execute() override {
        receiver->action();
    }
};
// 调用者
class Invoker {
private:
    std::vector<Command*> commands;

public:
    ~Invoker() {
        for (auto cmd : commands) {
            delete cmd;
        }
    }

    void addCommand(Command* cmd) {
        commands.push_back(cmd);
    }

    void executeCommands() {
        for (auto cmd : commands) {
            cmd->execute();
        }
    }
};

4.3 解释器模式 (Interpreter)

意图:给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。

#include <iostream>
#include <string>
#include <map>
// 抽象表达式
class Expression {
public:
    virtual ~Expression() {}
    virtual int interpret(std::map<std::string, int>& context) = 0;
};
// 终结符表达式
class TerminalExpression : public Expression {
private:
    std::string variable;

public:
    TerminalExpression(const std::string& var) : variable(var) {}

    int interpret(std::map<std::string, int>& context) override {
        return context[variable];
    }
};
// 非终结符表达式 - 加法
class AddExpression : public Expression {
private:
    Expression* left;
    Expression* right;

public:
    AddExpression(Expression* l, Expression* r) : left(l), right(r) {}

    ~AddExpression() {
        delete left;
        delete right;
    }

    int interpret(std::map<std::string, int>& context) override {
        return left->interpret(context) + right->interpret(context);
    }
};
// 非终结符表达式 - 减法
class SubtractExpression : public Expression {
private:
    Expression* left;
    Expression* right;

public:
    SubtractExpression(Expression* l, Expression* r) : left(l), right(r) {}

    ~SubtractExpression() {
        delete left;
        delete right;
    }

    int interpret(std::map<std::string, int>& context) override {
        return left->interpret(context) - right->interpret(context);
    }
};

4.4 迭代器模式 (Iterator)

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

#include <vector>
#include <iostream>
// 迭代器接口
template <typename T>
class Iterator {
public:
    virtual ~Iterator() {}
    virtual T next() = 0;
    virtual bool hasNext() = 0;
};
// 具体迭代器
template <typename T>
class ConcreteIterator : public Iterator<T> {
private:
    std::vector<T> collection;
    size_t position;

public:
    ConcreteIterator(const std::vector<T>& coll) : collection(coll), position(0) {}

    T next() override {
        return collection[position++];
    }

    bool hasNext() override {
        return position < collection.size();
    }
};
// 聚合接口
template <typename T>
class Aggregate {
public:
    virtual ~Aggregate() {}
    virtual Iterator<T>* createIterator() = 0;
};
// 具体聚合
template <typename T>
class ConcreteAggregate : public Aggregate<T> {
private:
    std::vector<T> collection;

public:
    void add(T item) {
        collection.push_back(item);
    }

    Iterator<T>* createIterator() override {
        return new ConcreteIterator<T>(collection);
    }
};

4.5 中介者模式 (Mediator)

意图:用一个中介对象来封装一系列的对象交互。

#include <iostream>
#include <string>
// 同事类接口
class Colleague;
// 中介者接口
class Mediator {
public:
    virtual ~Mediator() {}
    virtual void notify(Colleague* sender, const std::string& event) = 0;
};
// 同事类
class Colleague {
protected:
    Mediator* mediator;

public:
    Colleague(Mediator* m = nullptr) : mediator(m) {}
    virtual ~Colleague() {}

    void setMediator(Mediator* m) {
        mediator = m;
    }
};
// 具体同事类1
class ConcreteColleague1 : public Colleague {
public:
    void doA() {
        std::cout << "Colleague1 does A" << std::endl;
        mediator->notify(this, "A");
    }

    void doB() {
        std::cout << "Colleague1 does B" << std::endl;
        mediator->notify(this, "B");
    }
};
// 具体同事类2
class ConcreteColleague2 : public Colleague {
public:
    void doC() {
        std::cout << "Colleague2 does C" << std::endl;
        mediator->notify(this, "C");
    }

    void doD() {
        std::cout << "Colleague2 does D" << std::endl;
        mediator->notify(this, "D");
    }
};
// 具体中介者
class ConcreteMediator : public Mediator {
private:
    ConcreteColleague1* colleague1;
    ConcreteColleague2* colleague2;

public:
    ConcreteMediator(ConcreteColleague1* c1, ConcreteColleague2* c2) 
        : colleague1(c1), colleague2(c2) {
        colleague1->setMediator(this);
        colleague2->setMediator(this);
    }

    void notify(Colleague* sender, const std::string& event) override {
        if (event == "A") {
            std::cout << "Mediator reacts on A and triggers:" << std::endl;
            colleague2->doC();
        } else if (event == "D") {
            std::cout << "Mediator reacts on D and triggers:" << std::endl;
            colleague1->doB();
        }
    }
};

4.6 备忘录模式 (Memento)

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

#include <iostream>
#include <string>
// 备忘录
class Memento {
private:
    std::string state;

public:
    Memento(const std::string& s) : state(s) {}

    std::string getState() const {
        return state;
    }
};
// 发起人
class Originator {
private:
    std::string state;

public:
    void setState(const std::string& s) {
        state = s;
    }

    std::string getState() const {
        return state;
    }

    Memento* saveStateToMemento() {
        return new Memento(state);
    }

    void getStateFromMemento(Memento* memento) {
        state = memento->getState();
    }
};
// 管理者
class CareTaker {
private:
    std::vector<Memento*> mementos;

public:
    ~CareTaker() {
        for (auto m : mementos) {
            delete m;
        }
    }

    void add(Memento* m) {
        mementos.push_back(m);
    }

    Memento* get(int index) {
        if (index >= 0 && index < mementos.size()) {
            return mementos[index];
        }
        return nullptr;
    }
};

4.7 观察者模式 (Observer)

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

#include <iostream>
#include <vector>
#include <algorithm>
// 观察者接口
class Observer {
public:
    virtual ~Observer() {}
    virtual void update(const std::string& message) = 0;
};
// 主题接口
class Subject {
private:
    std::vector<Observer*> observers;

public:
    virtual ~Subject() {}

    void attach(Observer* observer) {
        observers.push_back(observer);
    }

    void detach(Observer* observer) {
        observers.erase(std::remove(observers.begin(), observers.end(), observer), observers.end());
    }

    void notify(const std::string& message) {
        for (auto observer : observers) {
            observer->update(message);
        }
    }
};
// 具体主题
class ConcreteSubject : public Subject {
private:
    std::string state;

public:
    void setState(const std::string& s) {
        state = s;
        notify(state);
    }

    std::string getState() const {
        return state;
    }
};
// 具体观察者
class ConcreteObserver : public Observer {
private:
    std::string name;

public:
    ConcreteObserver(const std::string& n) : name(n) {}

    void update(const std::string& message) override {
        std::cout << "Observer " << name << " received message: " << message << std::endl;
    }
};

4.8 状态模式 (State)

意图:允许一个对象在其内部状态改变时改变它的行为。

#include <iostream>
// 状态接口
class State {
public:
    virtual ~State() {}
    virtual void handle() = 0;
};
// 具体状态A
class ConcreteStateA : public State {
public:
    void handle() override {
        std::cout << "Handling in State A" << std::endl;
    }
};
// 具体状态B
class ConcreteStateB : public State {
public:
    void handle() override {
        std::cout << "Handling in State B" << std::endl;
    }
};
// 上下文
class Context {
private:
    State* state;

public:
    Context(State* s) : state(s) {}

    ~Context() {
        delete state;
    }

    void setState(State* s) {
        delete state;
        state = s;
    }

    void request() {
        state->handle();
    }
};

4.9 策略模式 (Strategy)

意图:定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。

#include <iostream>
// 策略接口
class Strategy {
public:
    virtual ~Strategy() {}
    virtual void execute() = 0;
};
// 具体策略A
class ConcreteStrategyA : public Strategy {
public:
    void execute() override {
        std::cout << "Executing strategy A" << std::endl;
    }
};
// 具体策略B
class ConcreteStrategyB : public Strategy {
public:
    void execute() override {
        std::cout << "Executing strategy B" << std::endl;
    }
};
// 上下文
class Context {
private:
    Strategy* strategy;

public:
    Context(Strategy* s) : strategy(s) {}

    ~Context() {
        delete strategy;
    }

    void setStrategy(Strategy* s) {
        delete strategy;
        strategy = s;
    }

    void executeStrategy() {
        strategy->execute();
    }
};

4.10 模板方法模式 (Template Method)

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

#include <iostream>
// 抽象类
class AbstractClass {
public:
    virtual ~AbstractClass() {}

    // 模板方法
    void templateMethod() {
        primitiveOperation1();
        primitiveOperation2();
    }

    virtual void primitiveOperation1() = 0;
    virtual void primitiveOperation2() = 0;
};
// 具体类
class ConcreteClass : public AbstractClass {
public:
    void primitiveOperation1() override {
        std::cout << "ConcreteClass primitive operation 1" << std::endl;
    }

    void primitiveOperation2() override {
        std::cout << "ConcreteClass primitive operation 2" << std::endl;
    }
};

4.11 访问者模式 (Visitor)

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

#include <iostream>
#include <vector>
// 前向声明
class ConcreteElementA;
class ConcreteElementB;
// 访问者接口
class Visitor {
public:
    virtual ~Visitor() {}
    virtual void visit(ConcreteElementA* element) = 0;
    virtual void visit(ConcreteElementB* element) = 0;
};
// 元素接口
class Element {
public:
    virtual ~Element() {}
    virtual void accept(Visitor* visitor) = 0;
};
// 具体元素A
class ConcreteElementA : public Element {
public:
    void accept(Visitor* visitor) override {
        visitor->visit(this);
    }

    std::string operationA() {
        return "ConcreteElementA";
    }
};
// 具体元素B
class ConcreteElementB : public Element {
public:
    void accept(Visitor* visitor) override {
        visitor->visit(this);
    }

    std::string operationB() {
        return "ConcreteElementB";
    }
};
// 具体访问者
class ConcreteVisitor : public Visitor {
public:
    void visit(ConcreteElementA* element) override {
        std::cout << "Visitor is processing " << element->operationA() << std::endl;
    }

    void visit(ConcreteElementB* element) override {
        std::cout << "Visitor is processing " << element->operationB() << std::endl;
    }
};
// 对象结构
class ObjectStructure {
private:
    std::vector<Element*> elements;

public:
    ~ObjectStructure() {
        for (auto e : elements) {
            delete e;
        }
    }

    void add(Element* element) {
        elements.push_back(element);
    }

    void accept(Visitor* visitor) {
        for (auto e : elements) {
            e->accept(visitor);
        }
    }
};

五、设计模式的选择与应用

5.1 如何选择设计模式

  1. 分析问题:明确问题的本质和需求
  2. 匹配模式:寻找与问题匹配的设计模式
  3. 评估方案:考虑模式的优缺点和适用性
  4. 实现模式:根据具体需求调整模式实现

5.2 设计模式的组合使用

许多实际应用中会组合使用多种设计模式,例如:

  • MVC架构中组合使用观察者、策略和组合模式
  • 装饰器模式常与工厂模式一起使用
  • 访问者模式常与迭代器模式一起使用

5.3 设计模式的误用与避免

常见误用情况:

  1. 过度设计:在不必要的地方使用设计模式
  2. 模式滥用:强行使用不适合的模式
  3. 模式误解:错误理解模式的意图和适用场景 避免方法:
  4. 充分理解问题后再选择模式
  5. 从简单设计开始,必要时再引入模式
  6. 持续重构,保持设计的灵活性

六、总结

设计模式是软件设计经验的结晶,掌握它们可以帮助开发者设计出更加灵活、可维护和可扩展的系统。C++作为一种多范式编程语言,特别适合实现各种设计模式。通过本教程的学习,您应该已经对23种经典设计模式有了全面的了解。 记住,设计模式不是银弹,它们应该作为工具在适当的场景中使用,而不是为了使用模式而使用模式。在实际开发中,要根据具体问题和需求灵活选择和调整设计模式。









results matching ""

    No results matching ""