我理解的装饰器模式
//定义一个原始的抽象类煎饼
class Pancake {
public:
std::string name;
int price = 0;
virtual ~Pancake() = default;
};
//具体的装饰器基类
class MeatPancake : public Pancake {
public:
MeatPancake() {
this->name = "肉煎饼";
this->price = 5;
}
};
//具体的装饰器基类
class EggPancake : public Pancake {
public:
EggPancake() {
this->name = "鸡蛋煎饼";
this->price = 3;
}
};
//抽象装饰类
class PancakeDecorator : public Pancake {
protected:
Pancake* _pancake = nullptr;//维护一个Pancake对象的引用,为Pancake对象添加装饰
public:
explicit PancakeDecorator(Pancake* pancake) : _pancake(pancake) {
}
~PancakeDecorator() override = default;
};
class Egg : public PancakeDecorator {
public:
explicit Egg(Pancake* pancake) : PancakeDecorator(pancake) {
this->name = pancake->name + " + 鸡蛋";
this->price = pancake->price + 2;
std::cout << this->name << " price: " << this->price << std::endl;
}
};
class Potato : public PancakeDecorator {
public:
explicit Potato(Pancake* pancake) : PancakeDecorator(pancake) {
this->name = pancake->name + " + 土豆";
this->price = pancake->price + 3;
std::cout << this->name << " price: " << this->price << std::endl;
}
};
EggPancake* eggPancake = new EggPancake();
Egg* egg = new Egg(eggPancake);
Potato* potato = new Potato(egg);
鸡蛋煎饼 + 鸡蛋 price: 5
鸡蛋煎饼 + 鸡蛋 + 土豆 price: 8
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论