Skip to content

装饰者模式

https://www.jianshu.com/p/f7d38078047b https://blog.51cto.com/u_15753490/5581734

装饰模式指的是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。

代码示例

#include <iostream>

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

class IPhone : public Phone {
public:
    IPhone() {}
    virtual void show () { std::cout << "show: " << name_ << std::endl; }

    std::string name_{"IPhone"};
};

//装饰者抽象类
class Decorator : public Phone {
public:
    Decorator(Phone *phone) : phone_(phone) {}
    virtual void show() { phone_->show(); }

    Phone *phone_;
};
//给手机装饰A功能
class DecoratorA : public Decorator {
public:
    DecoratorA(Phone *phone) : Decorator(phone) {}
    virtual void show() {
        Decorator::show();
        std::cout << "DecoratorA add A func" << std::endl;
    }
};
//给手机装饰B功能
class DecoratorB : public Decorator {
public:
    DecoratorB(Phone *phone) : Decorator(phone) {}
    virtual void show() {
        Decorator::show();
        std::cout << "DecoratorB add B func" << std::endl;
    }
};


int main() {
    Phone *phone = new IPhone();
    Phone *decoratorA = new DecoratorA(phone);
    Phone *decoratorB = new DecoratorB(phone);

    decoratorA->show();
    decoratorB->show();

    delete phone;
    delete decoratorA;
    delete decoratorB;

    return 0;
}