装饰者模式:动态地为对象添加额外的职责;
Component:对象接口;
Decorator:装饰抽象类,从外类来扩展Component的功能,但对于Component而言,是无需知道Decorator类的存在的;
ConcreteDecorator:就是具体的装饰对象类,起到给Component增添职责的功能;
装饰模式:是为已有功能动态添加更多功能的一种方式,它将每个要装饰的功能放在单独的类中,并让这个类包含它要装饰的对象;因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择得、按照顺序的使用装饰功能来包装对象了;
装饰模式优点 :把类的装饰功能从类中搬除,可以简化原有的类,有效地将类的核心职责与装饰功能区分开,而且可以去除相关类中重复的装饰逻辑;
代码示例:
待装饰对象、装饰者类及具体装饰品类定义和实现如下:
#ifndef PERSON_H
#define PERSON_H
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
Person(){}
Person(string strname)
{
name = strname;
}
virtual void show()
{
cout << "Decorate xiao cai " << endl;
}
private:
string name;
};
class Finery:public Person
{
public:
void decorate(Person *mcomponent)
{
component=mcomponent;
}
void show()
{
component->show();
}
protected:
Person *component;
};
class TShirts:public Finery
{
public:
void show()
{
cout << "TShirts ";
component->show();
}
};
class BigTrouser:public Finery
{
public:
void show()
{
cout << "BigTrouser ";
component->show();
}
};
#endif
客户端代码如下:
#include "person.h"
int main()
{
Person *xc = new Person("xiaocai");
cout << "first decorator is following:" << endl;
BigTrouser *bt = new BigTrouser();
TShirts *ts = new TShirts();
bt->decorate(xc);
ts->decorate(bt);
ts->show();
delete ts;
delete bt;
delete xc;
return 0;
}
最终输出如下: