装饰模式
理论
装饰模式:动态地给一个对象添加一些额外地职责,就增加功能来说,装饰模式比生成子类更加灵活。

装饰模式是为已有功能动态地添加更多功能地一种方式。当系统需要新功能的时候,是向旧的类中添加新的代码。这些新加的代码通常装饰了原有类的核心职责或主要行为。在主类中加入了新的字段,新的方法和新的逻辑,从而增加了主类的复杂度,而这些新加入的东西仅仅是为了满足一些只在某种特定情况下才能执行的特殊行为的需要。装饰模式提供了一个很好的解决方案,它把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择地、按顺序地使用装饰功能包装对象了。
优点:把类中地装饰功能从类中搬移去除,这样可以简化原有地类。有效地把类的核心职责和装饰功能分开了,而且可以去除相关类中重复地装饰逻辑。
实例
写一个可以给人搭配不同的服饰的系统
UML类图

实现代码
#include <iostream>
#include <string>
using namespace std;
//Person类
class Person{
public:
Person() {} //删除会无法引用子类(TShirts、BigTrouser...)的默认构造函数
Person(string name)
{
this->name = name;
}
virtual void show()
{
cout << "装扮的" << name << endl;
}
private:
string name;
};
//服饰类
class Finery: public Person{
public:
void Decorate(Person* component)
{
this->component = component;
}
virtual void show()
{
if(component != NULL)
{
component->show();
}
}
protected:
Person* component;
};
//具体服饰类
class TShirts: public Finery {
public:
virtual void show() {
cout << "大T恤 ";
Finery::show();
}
};
class BigTrouser: public Finery {
public:
virtual void show() {
cout << "垮裤 ";
Finery::show();
}
};
class Sneakers: public Finery {
public:
virtual void show() {
cout << "破球鞋 ";
Finery::show();
}
};
class Suit: public Finery {
public:
virtual void show() {
cout << "西装 ";
Finery::show();
}
};
class Tie: public Finery {
public:
virtual void show() {
cout << "领带 ";
Finery::show();
}
};
class LeatherShoes: public Finery {
public:
virtual void show() {
cout << "皮鞋 ";
Finery::show();
}
};
//客户端代码
void test()
{
Person* xc = new Person("小菜");
cout << "第一种装扮" << endl;
Sneakers* pqx = new Sneakers();
BigTrouser* kk = new BigTrouser();
TShirts* dtx = new TShirts();
pqx->Decorate(xc);
kk->Decorate(pqx);
dtx->Decorate(kk);
dtx->show();
cout << "-----------------------------" << endl;
cout << "第一种装扮" << endl;
LeatherShoes* px = new LeatherShoes();
Tie* ld = new Tie();
Suit* xz = new Suit();
px->Decorate(xc);
ld->Decorate(px);
xz->Decorate(ld);
xz->show();
}
int main()
{
test();
system("pause");
return 0;
}
运行结果


浙公网安备 33010602011771号