C++中的设计模式
设计模式是软件工程中用于解决常见问题的可复用解决方案。它们提供了一种标准化的方法来设计和实现软件系统,从而提高代码的可维护性、可扩展性和可重用性。C++ 是一种支持多种编程范式(如面向对象、泛型编程等)的语言,因此可以方便地实现各种设计模式。
以下是 C++ 中常见的设计模式,按类别进行分类:
创建型模式(Creational Patterns)
这些模式用于创建对象,同时隐藏创建逻辑,而不是直接使用 new
操作符实例化对象。
-
单例模式(Singleton)
-
目的:确保一个类只有一个实例,并提供一个全局访问点。
-
实现:通过私有化构造函数和析构函数,禁止拷贝构造和赋值操作,并提供一个静态方法来获取唯一的实例。
-
示例
class Singleton { private: static Singleton* instance; Singleton() {} // 私有化构造函数 public: static Singleton* getInstance() { if (instance == nullptr) { instance = new Singleton(); } return instance; } }; Singleton* Singleton::instance = nullptr;
-
-
工厂模式(Factory)
-
目的:定义一个创建对象的接口,让子类决定实例化哪一个类。
-
实现:创建一个工厂类,该类包含一个工厂方法,用于创建对象。
-
示例:
class Product { public: virtual void use() = 0; }; class ConcreteProductA : public Product { public: void use() override { std::cout << "Using ConcreteProductA" << std::endl; } }; class ConcreteProductB : public Product { public: void use() override { std::cout << "Using ConcreteProductB" << std::endl; } }; class Factory { public: virtual Product* createProduct() = 0; }; class ConcreteFactoryA : public Factory { public: Product* createProduct() override { return new ConcreteProductA(); } }; class ConcreteFactoryB : public Factory { public: Product* createProduct() override { return new ConcreteProductB(); } };
-
-
抽象工厂模式(Abstract Factory)
-
目的:创建相关或依赖对象的家族,而不需明确指定具体类。
-
实现:定义一个抽象工厂接口,包含多个工厂方法,每个方法创建一个具体的产品。
-
示例
// 省略具体实现,与工厂模式类似,但包含多个工厂方法
-
-
建造者模式(Builder)
-
目的:构建一个复杂的对象,并允许用户只通过指定复杂对象的类型和内容就能构建它们,隐藏了复杂对象的构建细节。
-
实现:创建一个建造者类,逐步构建对象,最后返回完整的对象。
-
示例
class Product { public: void setPartA() {} void setPartB() {} }; class Builder { public: virtual void buildPartA() = 0; virtual void buildPartB() = 0; virtual Product* getResult() = 0; }; class ConcreteBuilder : public Builder { private: Product* product; public: ConcreteBuilder() { product = new Product(); } void buildPartA() override { product->setPartA(); } void buildPartB() override { product->setPartB(); } Product* getResult() override { return product; } }; class Director { public: void construct(Builder* builder) { builder->buildPartA(); builder->buildPartB(); } };
-
-
原型模式(Prototype)
-
目的:通过复制现有的实例来创建新的实例,而不是通过新建实例。
-
实现:定义一个原型接口,包含一个克隆方法。
-
示例
class Prototype { public: virtual Prototype* clone() = 0; }; class ConcretePrototype : public Prototype { public: ConcretePrototype* clone() override { return new ConcretePrototype(*this); } };
-
结构型模式(Structural Patterns)
这些模式用于对象组合,通常用于实现对象间的关系,让它们能够协同工作。
-
适配器模式(Adapter)
-
目的:允许将不兼容的接口转换为一个兼容的接口。
-
实现:创建一个适配器类,实现目标接口,并在内部封装一个适配者对象。
-
示例
class Target { public: virtual void request() = 0; }; class Adaptee { public: void specificRequest() { std::cout << "Specific request" << std::endl; } }; class Adapter : public Target { private: Adaptee* adaptee; public: Adapter() { adaptee = new Adaptee(); } void request() override { adaptee->specificRequest(); } };
-
-
桥接模式(Bridge)
-
目的:将抽象与实现解耦,让它们可以独立变化。
-
实现:创建一个桥接接口,将抽象部分与实现部分分离。
-
示例
class Implementor { public: virtual void operationImpl() = 0; }; class ConcreteImplementorA : public Implementor { public: void operationImpl() override { std::cout << "ConcreteImplementorA" << std::endl; } }; class ConcreteImplementorB : public Implementor { public: void operationImpl() override { std::cout << "ConcreteImplementorB" << std::endl; } }; class Abstraction { protected: Implementor* implementor; public: Abstraction(Implementor* impl) : implementor(impl) {} virtual void operation() { implementor->operationImpl(); } }; class RefinedAbstraction : public Abstraction { public: RefinedAbstraction(Implementor* impl) : Abstraction(impl) {} void operation() override { std::cout << "RefinedAbstraction" << std::endl; Abstraction::operation(); } };
-
-
组合模式(Composite)
-
目的:将对象组合成树形结构以表示“部分-整体”的层次结构。
-
实现:创建一个组件接口,定义叶子节点和组合节点的行为。
-
示例
class Component { public: virtual void operation() = 0; virtual void add(Component* component) {} virtual void remove(Component* component) {} }; class Leaf : public Component { public: void operation() override { std::cout << "Leaf operation" << std::endl; } }; class Composite : public Component { private: std::vector<Component*> children; public: void operation() override { std::cout << "Composite operation" << std::endl; for (auto* child : children) { child->operation(); } } void add(Component* component) override { children.push_back(component); } void remove(Component* component) override { children.erase(std::remove(children.begin(), children.end(), component), children.end()); } };
-
-
装饰器模式(Decorator)
-
目的:动态地给一个对象添加额外的职责。
-
实现:创建一个装饰器类,继承自目标类,并在内部封装一个目标对象。
-
示例
class Component { public: 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* comp) : component(comp) {} void operation() override { component->operation(); } }; class ConcreteDecoratorA : public Decorator { public: ConcreteDecoratorA(Component* comp) : Decorator(comp) {} void operation() override { std::cout << "ConcreteDecoratorA operation" << std::endl; Decorator::operation(); } }; class ConcreteDecoratorB : public Decorator { public: ConcreteDecoratorB(Component* comp) : Decorator(comp) {} void operation() override { std::cout << "ConcreteDecoratorB operation" << std::endl; Decorator::operation(); } };
-
-
外观模式(Facade)
-
目的:提供一个统一的高层接口,用于访问子系统中的一群接口。
-
实现:创建一个外观类,封装子系统的复杂性。
-
示例
class SubsystemA { public: void operationA() { std::cout << "SubsystemA operation" << std::endl; } }; class SubsystemB { public: void operationB() { std::cout << "SubsystemB operation" << std::endl; } }; class Facade { private: SubsystemA* subsystemA; SubsystemB* subsystemB; public: Facade() { subsystemA = new SubsystemA(); subsystemB = new SubsystemB(); } void operation() { subsystemA->operationA(); subsystemB->operationB(); } };
-
-
享元模式(Flyweight)
-
目的:通过共享来高效地支持大量细粒度的对象。
-
实现:创建一个享元工厂,管理共享对象。
-
示例
class Flyweight { public: virtual void operation() = 0; }; class ConcreteFlyweight : public Flyweight { public: void operation() override { std::cout << "ConcreteFlyweight operation" << std::endl; } }; class FlyweightFactory { private: std::map<std::string, Flyweight*> flyweights; public: Flyweight* getFlyweight(const std::string& key) { if (flyweights.find(key) == flyweights.end()) { flyweights[key] = new ConcreteFlyweight(); } return flyweights[key]; } };
-
-
代理模式(Proxy)
-
目的:为其他对象提供一种代理,以控制对这个对象的访问。
-
实现:创建一个代理类,实现与目标类相同的接口,并在内部封装一个目标对象。
-
示例
class Subject { public: 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; public: void request() override { if (realSubject == nullptr) { realSubject = new RealSubject(); } realSubject->request(); } };
-
行为型模式(Behavioral Patterns)
这些模式用于对象间的行为和通信,通常用于实现对象间复杂的交互。
-
策略模式(Strategy)
-
目的:定义一系列算法,把它们一个个封装起来,并使它们可互换。
-
实现:创建一个策略接口,定义算法的接口,并在具体策略类中实现算法。
-
示例
class Strategy { public: virtual void algorithmInterface() = 0; }; class ConcreteStrategyA : public Strategy { public: void algorithmInterface() override { std::cout << "ConcreteStrategyA algorithm" << std::endl; } }; class ConcreteStrategyB : public Strategy { public: void algorithmInterface() override { std::cout << "ConcreteStrategyB algorithm" << std::endl; } }; class Context { private: Strategy* strategy; public: Context(Strategy* strat) : strategy(strat) {} void setStrategy(Strategy* strat) { strategy = strat; } void contextInterface() { strategy->algorithmInterface(); } };
-
-
模板方法模式(Template Method)
-
目的:定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。
-
实现:创建一个抽象类,定义算法的骨架,并在子类中实现具体步骤。
-
示例
class AbstractClass { public: void templateMethod() { primitiveOperation1(); primitiveOperation2(); } protected: virtual void primitiveOperation1() = 0; virtual void primitiveOperation2() = 0; }; class ConcreteClassA : public AbstractClass { protected: void primitiveOperation1() override { std::cout << "ConcreteClassA primitiveOperation1" << std::endl; } void primitiveOperation2() override { std::cout << "ConcreteClassA primitiveOperation2" << std::endl; } }; class ConcreteClassB : public AbstractClass { protected: void primitiveOperation1() override { std::cout << "ConcreteClassB primitiveOperation1" << std::endl; } void primitiveOperation2() override { std::cout << "ConcreteClassB primitiveOperation2" << std::endl; } };
-
-
观察者模式(Observer)
-
目的:定义对象间的一对多依赖关系,当一个对象改变状态时,所有依赖于它的对象都会得到通知并自动更新。
-
实现:创建一个主题接口和观察者接口,主题维护观察者列表,并在状态改变时通知观察者。
-
示例
class Observer { public: virtual void update() = 0; }; class Subject { private: std::vector<Observer*> observers; public: 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() { for (auto* observer : observers) { observer->update(); } } }; class ConcreteObserverA : public Observer { public: void update() override { std::cout << "ConcreteObserverA update" << std::endl; } }; class ConcreteObserverB : public Observer { public: void update() override { std::cout << "ConcreteObserverB update" << std::endl; } };
-
-
迭代器模式(Iterator)
-
目的:提供一种顺序访问一个聚合对象中各个元素的方法,而不暴露其内部的表示。
-
实现:创建一个迭代器接口,定义遍历聚合对象的方法。
-
示例
class Iterator { public: virtual void first() = 0; virtual void next() = 0; virtual bool isDone() = 0; virtual int currentItem() = 0; }; class Aggregate { public: virtual Iterator* createIterator() = 0; }; class ConcreteAggregate : public Aggregate { private: std::vector<int> items; public: ConcreteAggregate() { items = {1, 2, 3, 4, 5}; } Iterator* createIterator() override { return new ConcreteIterator(this); } int getAt(int index) { return items[index]; } int size() { return items.size(); } }; class ConcreteIterator : public Iterator { private: ConcreteAggregate* aggregate; int current; public: ConcreteIterator(ConcreteAggregate* agg) : aggregate(agg), current(0) {} void first() override { current = 0; } void next() override { current++; } bool isDone() override { return current >= aggregate->size(); } int currentItem() override { return aggregate->getAt(current); } };
-
-
责任链模式(Chain of Responsibility)
-
目的:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。
-
实现:创建一个处理者接口,定义处理请求的方法,并在具体处理者中实现具体的处理逻辑。
-
示例
class Handler { protected: Handler* successor; public: Handler(Handler* succ) : successor(succ) {} virtual void handleRequest(int request) { if (successor != nullptr) { successor->handleRequest(request); } } }; class ConcreteHandlerA : public Handler { public: ConcreteHandlerA(Handler* succ) : Handler(succ) {} void handleRequest(int request) override { if (request >= 0 && request < 10) { std::cout << "ConcreteHandlerA handled request" << std::endl; } else { Handler::handleRequest(request); } } }; class ConcreteHandlerB : public Handler { public: ConcreteHandlerB(Handler* succ) : Handler(succ) {} void handleRequest(int request) override { if (request >= 10 && request < 20) { std::cout << "ConcreteHandlerB handled request" << std::endl; } else { Handler::handleRequest(request); } } };
-
-
命令模式(Command)
-
目的:将一个请求封装为一个对象,从而使用户可用不同的请求对客户进行参数化。
-
实现:创建一个命令接口,定义执行操作的方法,并在具体命令类中实现具体的操作。
-
示例
class Receiver { public: void action() { std::cout << "Receiver action" << std::endl; } }; class Command { public: virtual void execute() = 0; }; class ConcreteCommand : public Command { private: Receiver* receiver; public: ConcreteCommand(Receiver* recv) : receiver(recv) {} void execute() override { receiver->action(); } }; class Invoker { private: Command* command; public: void setCommand(Command* cmd) { command = cmd; } void executeCommand() { command->execute(); } };
-
-
备忘录模式(Memento)
-
目的:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。
-
实现:创建一个备忘录类,保存对象的状态,并在发起人和管理者之间传递备忘录。
-
示例
class Memento { private: std::string state; public: Memento(const std::string& state) : state(state) {} std::string getState() { return state; } }; class Originator { private: std::string state; public: void setState(const std::string& state) { this->state = state; } std::string getState() { return state; } Memento* createMemento() { return new Memento(state); } void setMemento(Memento* memento) { state = memento->getState(); } }; class Caretaker { private: Memento* memento; public: void save(Originator* originator) { memento = originator->createMemento(); } void undo(Originator* originator) { originator->setMemento(memento); } };
-
-
状态模式(State)
-
目的:允许一个对象在其内部状态改变时改变其行为。
-
实现:创建一个状态接口,定义状态的行为,并在具体状态类中实现具体的行为。
-
示例
class Context { private: State* state; public: Context(State* state) : state(state) {} void setState(State* state) { this->state = state; } void request() { state->handle(this); } }; class State { public: virtual void handle(Context* context) = 0; }; class ConcreteStateA : public State { public: void handle(Context* context) override { std::cout << "ConcreteStateA handle" << std::endl; context->setState(new ConcreteStateB()); } }; class ConcreteStateB : public State { public: void handle(Context* context) override { std::cout << "ConcreteStateB handle" << std::endl; context->setState(new ConcreteStateA()); } };
-
-
访问者模式(Visitor)
-
目的:为一个对象结构中的对象添加新的能力。
-
实现:创建一个访问者接口,定义访问对象的方法,并在具体访问者类中实现具体的访问逻辑。
-
示例
class Element { public: virtual void accept(Visitor* visitor) = 0; }; class ConcreteElementA : public Element { public: void accept(Visitor* visitor) override { visitor->visitConcreteElementA(this); } }; class ConcreteElementB : public Element { public: void accept(Visitor* visitor) override { visitor->visitConcreteElementB(this); } }; class Visitor { public: virtual void visitConcreteElementA(ConcreteElementA* element) = 0; virtual void visitConcreteElementB(ConcreteElementB* element) = 0; }; class ConcreteVisitor : public Visitor { public: void visitConcreteElementA(ConcreteElementA* element) override { std::cout << "ConcreteVisitor visitConcreteElementA" << std::endl; } void visitConcreteElementB(ConcreteElementB* element) override { std::cout << "ConcreteVisitor visitConcreteElementB" << std::endl; } };
-
-
中介者模式(Mediator)
-
目的:用一个中介对象来封装一系列的对象交互。
-
实现:创建一个中介者接口,定义协调对象交互的方法,并在具体中介者类中实现具体的协调逻辑。
-
示例
class Mediator { public: virtual void notify(Component* component, const std::string& event) = 0; }; class Component { protected: Mediator* mediator; public: Component(Mediator* mediator) : mediator(mediator) {} virtual void doA() = 0; virtual void doB() = 0; }; class ConcreteComponentA : public Component { public: ConcreteComponentA(Mediator* mediator) : Component(mediator) {} void doA() override { std::cout << "ConcreteComponentA doA" << std::endl; mediator->notify(this, "A"); } void doB() override { std::cout << "ConcreteComponentA doB" << std::endl; } }; class ConcreteComponentB : public Component { public: ConcreteComponentB(Mediator* mediator) : Component(mediator) {} void doA() override { std::cout << "ConcreteComponentB doA" << std::endl; } void doB() override { std::cout << "ConcreteComponentB doB" << std::endl; mediator->notify(this, "B"); } }; class ConcreteMediator : public Mediator { private: ConcreteComponentA* componentA; ConcreteComponentB* componentB; public: ConcreteMediator(ConcreteComponentA* a, ConcreteComponentB* b) : componentA(a), componentB(b) {} void notify(Component* component, const std::string& event) override { if (component == componentA && event == "A") { componentB->doB(); } else if (component == componentB && event == "B") { componentA->doA(); } } };
-
这些设计模式在实际开发中非常有用,可以帮助你设计出更加灵活、可维护和可扩展的系统。选择合适的设计模式需要根据具体问题和需求来决定。