C++ 23种设计模式概述以及代码示例学习

以下是23种经典设计模式的简要概述以及C++代码示例:

1. 单例模式 (Singleton Pattern):

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

   cpp

   class Singleton {

   public:

       static Singleton& getInstance() {

           static Singleton instance;

           return instance;

       }

   private:

       Singleton() {} // Private constructor to prevent instantiation

   };

  

2. 工厂方法模式 (Factory Method Pattern):

   定义一个接口,但将对象的创建交给子类。

  cpp

   class Product {

   public:

       virtual void create() = 0;

   };


   class ConcreteProduct : public Product {

   public:

       void create() override {

           // Create product

       }

   };

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

   提供一个接口,用于创建一系列相关对象,而不指定具体类。


 

  cpp

   class AbstractFactory {

   public:

       virtual AbstractProductA* createProductA() = 0;

       virtual AbstractProductB* createProductB() = 0;

   };


   class ConcreteFactory : public AbstractFactory {

   public:

       AbstractProductA* createProductA() override {

           return new ConcreteProductA();

       }

       AbstractProductB* createProductB() override {

           return new ConcreteProductB();

       }

   };

   

4. 建造者模式 (Builder Pattern):

   将一个复杂对象的构建与表示分离,允许相同的构建过程创建不同的表示。

   cpp

   class Product {

   public:

       void setPartA(const std::string& partA) {

           // Set part A

       }

       void setPartB(const std::string& partB) {

           // Set part B

       }

   };

   

   class Builder {

   public:

       virtual void buildPartA() = 0;

       virtual void buildPartB() = 0;

       virtual Product* getResult() = 0;

   };


   class ConcreteBuilder : public Builder {

   private:

       Product product;

   public:

       void buildPartA() override {

           product.setPartA("Part A");

       }

       void buildPartB() override {

           product.setPartB("Part B");

       }

       Product* getResult() override {

           return &product;

       }

   };

   

5. 原型模式 (Prototype Pattern):

   通过复制现有对象来创建新对象,而不是使用构造函数。


   

cpp

   class Prototype {

   public:

       virtual Prototype* clone() = 0;

   };


   class ConcretePrototype : public Prototype {

   public:

       Prototype* clone() override {

           return new ConcretePrototype(*this);

       }

   };

   

6. 适配器模式 (Adapter Pattern):

   允许接口不兼容的类协同工作。

   cpp

   class Target {

   public:

       virtual void request() = 0;

   };


   class Adaptee {

   public:

       void specificRequest() {

           // Specific request

       }

   };


   class Adapter : public Target {

   private:

       Adaptee* adaptee;

   public:

       Adapter(Adaptee* a) : adaptee(a) {}

       void request() override {

           adaptee->specificRequest();

       }

   };

   

7. 桥接模式 (Bridge Pattern):

   将抽象部分与其实现分离,以便二者可以独立变化。


   

cpp

   class Implementor {

   public:

       virtual void operation() = 0;

   };


   class ConcreteImplementorA : public Implementor {

   public:

       void operation() override {

           // Implementation A

       }

   };


   class ConcreteImplementorB : public Implementor {

   public:

       void operation() override {

           // Implementation B

       }

   };


   class Abstraction {

   protected:

       Implementor* implementor;

   public:

       Abstraction(Implementor* imp) : implementor(imp) {}

       virtual void operation() = 0;

   };


   class RefinedAbstraction : public Abstraction {

   public:

       RefinedAbstraction(Implementor* imp) : Abstraction(imp) {}

       void operation() override {

           // Some operation

           implementor->operation();

       }

   };

   

8. 组合模式 (Composite Pattern):

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


  

 cpp

   class Component {

   public:

       virtual void operation() = 0;

   };


   class Leaf : public Component {

   public:

       void operation() override {

           // Leaf operation

       }

   };


   class Composite : public Component {

   private:

       std::vector<Component*> children;

   public:

       void add(Component* component) {

           children.push_back(component);

       }

       void operation() override {

           // Composite operation

           for (Component* child : children) {

               child->operation();

           }

       }

   };

   

9. 装饰器模式 (Decorator Pattern):

   动态地为对象添加额外的职责。


   

cpp

   class Component {

   public:

       virtual void operation() = 0;

   };


   class ConcreteComponent : public Component {

   public:

       void operation() override {

           // Base operation

       }

   };


   class Decorator : public Component {

   private:

       Component* component;

   public:

       Decorator(Component* comp) : component(comp) {}

       void operation() override {

           component->operation();

       }

   };


   class ConcreteDecorator : public Decorator {

   public:

       ConcreteDecorator(Component* comp) : Decorator(comp) {}

       void addedBehavior() {

           // Additional behavior

       }

       void operation() override {

           Decorator::operation();

           addedBehavior();

       }

   };

  

10. 外观模式 (Facade Pattern):

    为子系统提供一个统一接口,以简化客户端与子系统之间的交互。
    

cpp

    class SubsystemA {

    public:

        void operationA() {

            // Subsystem A operation

        }

    };


    class SubsystemB {

    public:

        void operationB() {

            // Subsystem B operation

        }

    };


    class Facade {

    private:

        SubsystemA subsystemA;

        SubsystemB subsystemB;

    public:

        void operation() {

            subsystemA.operationA();

            subsystemB.operationB();

        }

    };

11. 享元模式 (Flyweight Pattern):

    共享细粒度对象,以减少内存和提高性能。
    

cpp

    class Flyweight {

    public:

        virtual void operation() = 0;

    };


    class ConcreteFlyweight : public Flyweight {

    private:

        std::string intrinsicState;

    public:

        ConcreteFlyweight(const std::string& intrinsic) : intrinsicState(intrinsic) {}

        void operation() override {

            // Use intrinsic state

        }

    };


    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(key);

            }

            return flyweights[key];

        }

    };

   

12. 代理模式 (Proxy Pattern):

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

cpp

    class Subject {

    public:

        virtual void request() = 0;

    };


    class RealSubject : public Subject {

    public:

        void request() override {

            // Real subject operation

        }

    };


    class Proxy : public Subject {

    private:

        RealSubject* realSubject;

    public:

        Proxy() : realSubject(nullptr) {}

        void request() override {

            if (!realSubject) {

                realSubject = new RealSubject();

            }

            realSubject->request();

        }

    };

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

    通过多个对象来处理请求,将请求沿处理链传递,直到有对象处理它为止。


   

 cpp

    class Handler {

    private:

        Handler* successor;

    public:

        void setSuccessor(Handler* next) {

            successor = next;

        }

        virtual void handleRequest(int request) = 0;

    };


    class ConcreteHandler : public Handler {

    public:

        void handleRequest(int request) override {

            if (request <= 10) {

                // Handle the request

            } else if (successor) {

                successor->handleRequest(request);

            }

        }

    };

 

14. 命令模式 (Command Pattern):

    将请求封装成对象,以允许参数化请求、将请求排队或记录请求日志,并支持可撤销的操作。


    

cpp

    class Command {

    public:

        virtual void execute() = 0;

    };


    class Receiver {

    public:

        void action() {

            // Perform action

        }

    };


    class ConcreteCommand : public Command {

    private:

        Receiver receiver;

    public:

        ConcreteCommand(Receiver rec) : receiver(rec) {}

        void execute() override {

            receiver.action();

        }

    };


    class Invoker {

    private:

        Command* command;

    public:

        void setCommand(Command* cmd) {

            command = cmd;

        }

        void executeCommand() {

            command->execute();

        }

    };

   

15. 中介者模式 (Mediator Pattern):

    减少对象之间的直接通信,通过中介者对象来协调它们的交互。


    

cpp

    class Colleague {

    public:

        virtual void send(const std::string& message) = 0;

        virtual void receive(const std::string& message) = 0;

    };


    class ConcreteColleague : public Colleague {

    private:

        Mediator* mediator;

    public:

        ConcreteColleague(Mediator* med) : mediator(med) {}

        void send(const std::string& message) override {

            mediator->send(message, this);

        }

        void receive(const std::string& message) override {

            // Receive and process the message

        }

    };


    class Mediator {

    public:

        virtual void send(const std::string& message, Colleague* colleague) = 0;

    };


    class ConcreteMediator : public Mediator {

    private:

        ConcreteColleague* colleague1;

        ConcreteColleague* colleague2;

    public:

        void setColleague1(ConcreteColleague* col) {

            colleague1 = col;

        }

        void setColleague2(ConcreteColleague* col) {

            colleague2 = col;

        }

        void send(const std::string& message, Colleague* colleague) override {

            if (colleague == colleague1) {

                colleague2->receive(message);

            } else {

                colleague1->receive(message);

            }

        }

    };

   

16. 观察者模式 (Observer Pattern):

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


    

cpp

    class Observer {

    public:

        virtual void update() = 0;

    };


    class ConcreteObserver : public Observer {

    public:

        void update() override {

            // Update based on subject's state

        }

    };


    class Subject {

    private:

        std::vector<Observer*> observers;

    public:

        void attach(Observer* observer) {

            observers.push_back(observer);

        }

        void detach(Observer* observer) {

            // Remove observer from list

        }

        void notify() {

            for (Observer* observer : observers) {

                observer->update();

            }

        }

    };

   

17. 策略模式 (Strategy Pattern):

    定义一系列算法,封装它们,使它们可以互相替换,从而使客户端能够独立于算法的变化。


    

cpp

    class Strategy {

    public:

        virtual void execute() = 0;

    };


    class ConcreteStrategyA : public Strategy {

    public:

        void execute() override {

            // Strategy A

        }

    };


    class ConcreteStrategyB : public Strategy {

    public:

        void execute() override {

            // Strategy B

        }

    };


    class Context {

    private:

        Strategy* strategy;

    public:

        void setStrategy(Strategy* strat) {

            strategy = strat;

        }

        void executeStrategy() {

            strategy->execute();

        }

    };

   

18. 状态模式 (State Pattern):

    允许对象在其内部状态发生改变时改变其行为。
 

   cpp

    class State {

    public:

        virtual void handle() = 0;

    };


    class ConcreteStateA : public State {

    public:

        void handle() override {

            // Handle state A

        }

    };


    class ConcreteStateB : public State {

    public:

        void handle() override {

            // Handle state B

        }

    };


    class Context {

    private:

        State* state;



    public:

        void setState(State* st) {

            state = st;

        }

        void request() {

            state->handle();

        }

    };

   

19. 访问者模式 (Visitor Pattern):

    将数据结构和算法分离,允许为数据结构添加新的操作而不需要修改其代码。

    

cpp

    class 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 {

            // Visit ConcreteElementA

        }

        void visitConcreteElementB(ConcreteElementB& element) override {

            // Visit ConcreteElementB

        }

    };

   

20. 策略模式 (Strategy Pattern):

    允许对象在其内部状态发生改变时改变其行为。

cpp

    class State {

    public:

        virtual void handle() = 0;

    };


    class ConcreteStateA : public State {

    public:

        void handle() override {

            // Handle state A

        }

    };


    class ConcreteStateB : public State {

    public:

        void handle() override {

            // Handle state B

        }

    };


    class Context {

    private:

        State* state;

    public:

        void setState(State* st) {

            state = st;

        }

        void request() {

            state->handle();

        }

    };


     

21. 备忘录模式 (Memento Pattern):

    允许对象的内部状态在不暴露其内部结构的情况下捕获并恢复。


    

cpp

    class Memento {

    private:

        std::string state;

    public:

        Memento(const std::string& st) : state(st) {}

        std::string getState() {

            return state;

        }

    };


    class Originator {

    private:

        std::string state;

    public:

        void setState(const std::string& st) {

            state = st;

        }

        Memento createMemento() {

            return Memento(state);

        }

        void restoreMemento(const Memento& memento) {

            state = memento.getState();

        }

    };


    class Caretaker {

    private:

        Memento memento;

    public:

        void saveMemento(const Memento& m) {

            memento = m;

        }

        Memento getMemento() {

            return memento;

        }

    };

   

22. 迭代器模式 (Iterator Pattern):

    提供一种顺序访问聚合对象元素的方法,而不需要暴露其内部表示。

 cpp

    class Iterator {

    public:

        virtual int next() = 0;

        virtual bool hasNext() = 0;

    };


    class ConcreteIterator : public Iterator {

    private:

        std::vector<int> collection;

        int position;

    public:

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

        int next() override {

            return collection[position++];

        }

        bool hasNext() override {

            return position < collection.size();

        }

    };


    class Aggregate {

    public:

        virtual Iterator* createIterator() = 0;

    };


    class ConcreteAggregate : public Aggregate {

    private:

        std::vector<int> collection;

    public:

        Iterator* createIterator() override {

            return new ConcreteIterator(collection);

        }

    };

23. 解释器模式 (Interpreter Pattern):

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

cpp

    class Expression {

    public:

        virtual bool interpret(const std::string& context) = 0;

    };


    class TerminalExpression : public Expression {

    private:

        std::string data;

    public:

        TerminalExpression(const std::string& d) : data(d) {}

        bool interpret(const std::string& context) override {

            return context.find(data) != std::string::npos;

        }

    };


    class OrExpression : public Expression {

    private:

        Expression* expr1;

        Expression* expr2;

    public:

        OrExpression(Expression* e1, Expression* e2) : expr1(e1), expr2(e2) {}

        bool interpret(const std::string& context) override {

            return expr1->interpret(context) || expr2->interpret(context);

        }

    };


    

   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

daolongzhang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值