装饰模式
//装饰模式:动态地给一个对象增加一些额外的职责
#include <iostream>
#include <string>
using namespace std;
class people {
public:
virtual int getValue() = 0;
};
class clothes :public people{
public:
virtual int getValue() {
return 80;
}
};
class Decoratorpeople :public clothes {
public:
people* m_p;
Decoratorpeople(people * p):m_p(p) {
}
virtual int getValue() {
return m_p->getValue();
}
};
class glassespeople :public Decoratorpeople {
public:
glassespeople(people *p):Decoratorpeople(p) {
}
virtual int getValue() {
return m_p->getValue() + 10;
}
};
class necklacepeople :public Decoratorpeople {
public:
necklacepeople(people* p) :Decoratorpeople(p) {}
virtual int getValue() {
return m_p->getValue() + 10;
}
};
int main() {
/*
增强型装饰者模式
如果增加功能的话可以增加decorator的子类即可
*/
people* f = new clothes;
cout << "穿衣服的人颜值:" << f->getValue() << endl;
Decoratorpeople* s = new glassespeople(f);
cout << "戴眼镜+床衣服的人颜值:" << s->getValue() << endl;
Decoratorpeople* t = new necklacepeople(s);
cout << "带项链 + 戴眼镜 + 床衣服的人颜值:" << t->getValue() << endl;
//Decoratorpeople* xxx = new necklacepeople(new necklacepeople(new clothes));
//cout << xxx->getValue() << endl;
return 0;
}