装饰模式

#include <iostream>
#include <memory>

class Component {
public:
    virtual void show() = 0;
};

class ConcreteComponent : public Component {
public:
    void show() override { std::cout << "In ConcreteComponent show()." << std::endl; }
};

class Decorator : public Component {
public:
    Decorator(std::shared_ptr<Component> cc) : cc(cc) {}
protected:
    std::shared_ptr<Component> cc = nullptr;
};

class ConcreteDecoratorA : public Decorator {
public:
    ConcreteDecoratorA(std::shared_ptr<Component> cc) : Decorator(cc) {}
    void show() override {
        std::cout << "In ConcreteDecoratorA show()." << std::endl;
        cc->show();
    }
};

class ConcreteDecoratorB : public Decorator {
public:
    ConcreteDecoratorB(std::shared_ptr<Component> cc) : Decorator(cc) {}
    void show() override {
        std::cout << "In ConcreteDecoratorB show()." << std::endl;
        cc->show();
    }
};

int main(int argc, char *argv[]) {
    std::shared_ptr<Component> cc = std::make_shared<ConcreteComponent>();
    std::shared_ptr<Component> d1c = std::make_shared<ConcreteDecoratorA>(cc);
    std::shared_ptr<Component> d2c = std::make_shared<ConcreteDecoratorB>(d1c);
    d2c->show();
    return 1;
}

  

posted @ 2022-02-25 17:50  南乡水  阅读(19)  评论(0编辑  收藏  举报