结构图
代码
# include <iostream>
using namespace std;
class person {
public :
person ( ) { } ;
person ( string name) { this -> name = name; }
virtual void show ( ) {
cout << "装扮的:" << this -> name << endl;
}
private :
string name;
} ;
class Finery : public person
{
public :
void Decorate ( person * component)
{
this -> component = component;
}
virtual void show ( ) override
{
if ( this -> component != nullptr )
{
this -> component-> show ( ) ;
}
}
protected :
person * component = nullptr ;
} ;
class T_short : public Finery
{
public :
void show ( ) override
{
cout << "T恤上衣" << endl;
Finery :: show ( ) ;
}
} ;
class jeansrawhem : public Finery
{
public :
void show ( ) override
{
cout << "破洞裤" << endl;
Finery :: show ( ) ;
}
} ;
class Beanie_shoes : public Finery
{
public :
void show ( ) override
{
cout << "豆豆鞋" << endl;
Finery :: show ( ) ;
}
} ;
int main ( )
{
person * xm = new person ( "小明" ) ;
Finery * fx = new Finery ( ) ;
T_short* ts = new T_short ( ) ;
jeansrawhem* js = new jeansrawhem ( ) ;
Beanie_shoes* bs = new Beanie_shoes ( ) ;
fx-> Decorate ( xm) ;
ts-> Decorate ( fx) ;
js-> Decorate ( ts) ;
bs-> Decorate ( js) ;
bs-> show ( ) ;
return 0 ;
}
总结
装饰模式 就是为已有功能添加更多功能的一种方式 当我们需要新的功能的时候 如果要往最开始的功能类里面添加新的功能 无疑会给原来的主类增加复杂度 而装饰模式会给每一个需要装饰功能单独设置一个类 我们需要那些类就去装载那些类 因此更方便的添加和删除功能 而不用去修改主类代码 把类中的装饰功能移除出去 可以简化原有的类 但是需要注意装饰的顺序问题 最理想的是保持类的相互独立 比如把每一个装饰的地方划分一个功能 上衣 裤子 鞋 之类的 让这些装饰类同时只能有一个单独的功能(西装上衣 体恤上衣 或者 卫衣)