装饰模式
动态的给一个对象添加一些额外的职责,就增加功能老说,装饰模式比生成子类更为灵活
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
在没有使用装饰模式之前,当系统需要新的功能的时候,是向旧类中添加新的代码,这些新加的代码通常装饰了原有类的核
心职责或主要行为,但在主类中添加新的字段,新的方法和逻辑,从而增加了主类的复杂度,而这些新加入的代码仅仅是为
了满足一些只在某种特殊情况下才会执行的特殊行为的需要,而装饰模式却提供了一个非常好的解决方案,它把每个要装饰
的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据
需要有选择的、按顺序的使用装饰功能包装对象了。
把类的装饰功能从类中搬出出去,可以简化原有的类,有效的把类的核心职责和装饰功能区分开了,而且可以去除相关类中
重复的装饰逻辑。
- 大小: 13.3 KB
分享到:
相关推荐
设计模式参考《大话设计模式》 工厂简单模式 创造型模式 工厂方法模式 抽象工厂模式 原型模式 建造者模式 单例模式 结构型模式 队列模式 桥接模式 组合模式 装饰模式 外观模式 享元模式 代理模式 行为模式(类行为...
《大话设计模式》对各种设计模式,做简要归纳(原创)
Android之大话设计模式——:抽象工厂模式借鉴.pdf
android之大话设计模式.pdf
大话设计模式源代码之简单工厂模式 经典代码
树懒自己整理的大话设计模式的修行笔记,对程序设计有很大的帮助,主要是以自己学习的习惯整理的!
android之大话设计模式整理.pdf
大话设计模式之外观模式 经典代码 C#类
NULL 博文链接:https://linxingliang.iteye.com/blog/1217811
大话设计模式 完整设计模式介绍
NULL 博文链接:https://helei050.iteye.com/blog/2086309
大话设计模式总结.pdf大话设计模式总结.pdf大话设计模式总结.pdf大话设计模式总结.pdf大话设计模式总结.pdf
设计模式之《大话设计模式》.pptx
大话设计模式源代码之策略模式 经典代码 C#类
大话设计模式之代理模式 经典代码 C#类
这是之前上传的大话设计模式书籍的对应程序,欢迎下载和阅读 这是之前上传的大话设计模式书籍的对应程序,欢迎下载和阅读
NULL 博文链接:https://forrest420.iteye.com/blog/1050306
大话设计模式源代码