装饰模式

#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;
}

 

上一篇:Swift之深入解析如何进行多重条件排序


下一篇:539 最小时间差