❤️强烈推荐人工智能学习网站❤️
今天来学习一下装饰模式,先看C++代码实现。
#include <iostream>
#include <string>
#include <math.h>
#include <stdlib.h>
using namespace std;
//装饰模式
class Person
{
public:
Person() {}
Person(string name)
{
this->name = name;
}
virtual void Show()
{
cout << name << endl;
}
private:
string name;
};
class Finery : public Person //服饰类
{
protected:
Person *component;
public:
Finery()
{
component = NULL;
}
void Decorate(Person *component)
{
this->component = component;
}
void Show()
{
if(component != NULL)
{
component->Show();
}
}
};
class Sneakers : public Finery
{
public:
void Show()
{
cout << "Sneakers" << endl;
Finery::Show();
}
};
class BigTrouser : public Finery
{
public:
void Show()
{
cout << "BigTrouser" << endl;
Finery::Show();
}
};
class TShirst : public Finery
{
public:
void Show()
{
cout << "TShirst" << endl;
Finery::Show();
}
};
int main()
{
Person *xc = new Person("xiaocai");
Sneakers *pqx = new Sneakers();
BigTrouser *kk = new BigTrouser();
TShirst *dtx = new TShirst();
pqx->Decorate(xc);
kk->Decorate(pqx);
dtx->Decorate(kk);
dtx->Show();
delete xc;
delete pqx;
delete kk;
delete dtx;
return 0;
}
上面代码思想是:"小菜"可以选择任意衣服进行装扮。Sneakers,BigTrouser,TShirst对象里面分别又可以显示自己功能 (上述代码没有实现),这样每个装饰类对象的实现就和如何使用这个对象分离开了。在main函数中,装饰过程是通过main函数代码和父类Finery的函数实现的,这样每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链中。装饰模式是为已有功能动态地添加更多功能的一种方式。
装饰模式优点:当类需要新增功能时,会向旧类中添加新的代码,这些代码会改变原有类核心职责或主要行为(而且有时候这些功能只是在特定的环境下才需要)。而装饰模式能规避这些,它把要装饰的功能单独放在一个类中,当要增加新的功能时,客户端直接装饰进去就可以,不需要修改旧类代码。
参考资料:大话设模式