装饰模式—大话设计模式(简约)
装饰模式
动态的给一个对象添加一些额外的职责,就增加功能老说,装饰模式比生成子类更为灵活
Component类
class Component {
public:
virtual void show() = 0;
};
ConcreteComponent类
class Person : public Component {
private:
char *name;
public:
Person(char *p_name) {
name = p_name;
}
void show();
};
void Person::show() {
cout<<"装扮的"<<name<<" ";
}
Decorator类
class Decorator : public Component {
protected:
Component *component;
public:
void decotate(Component *component);
void show();
};
void Decorator::decotate(Component *p_component) {
component = p_component;
}
void Decorator::show() {
if(NULL != component) {
component->show();
}
}
ConcreteDecorator类
class TShirts : public Decorator {
public:
void show() {
component->show();
cout<<"穿T恤"<<" ";
}
};
class XiFu : public Decorator {
public:
void show() {
component->show();
cout<<"穿西服"<<" ";
}
};
class KuZi : public Decorator {
public:
void show() {
component->show();
cout<<"穿裤子"<<" ";
}
};
class Showes : public Decorator {
public:
void show() {
component->show();
cout<<"穿鞋子"<<" ";
}
};
测试函数
int main(void) {
Person *person = new Person("LiNing");
TShirts *tshirts = new TShirts();
XiFu *xifu = new XiFu();
KuZi *kuzi = new KuZi();
Showes *showes = new Showes();
tshirts->decotate(person);
kuzi->decotate(tshirts);
xifu->decotate(kuzi);
showes->decotate(xifu);
showes->show();
return 0;
}
输出结果
装扮的LiNing 穿T恤 穿裤子 穿西服 穿鞋子 Press any key to continue
在没有使用装饰模式之前,当系统需要新的功能的时候,是向旧类中添加新的代码,这些新加的代码通常装饰了原有类的核
心职责或主要行为,但在主类中添加新的字段,新的方法和逻辑,从而增加了主类的复杂度,而这些新加入的代码仅仅是为
了满足一些只在某种特殊情况下才会执行的特殊行为的需要,而装饰模式却提供了一个非常好的解决方案,它把每个要装饰
的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据
需要有选择的、按顺序的使用装饰功能包装对象了。
把类的装饰功能从类中搬出出去,可以简化原有的类,有效的把类的核心职责和装饰功能区分开了,而且可以去除相关类中
重复的装饰逻辑。