您的位置:首页 > 编程语言 > C语言/C++

设计模式之装饰者模式(c++实现)

2014-09-13 15:00 661 查看

装饰者模式简介

装饰者模式:就像是俄罗斯套娃,一个套一个,每套一次,外形和体积都发生了变化,但是本质还是个俄罗斯娃娃
官方的定义:动态地将责任附加到对象上,若要扩展功能,装饰者提供了比继承者更有弹性的替代方案。

装饰者模式也是用组合替代继承的一个典型应用,这里的组合就是通过一层一层的套上去来实现的

示例代码类图

示例代码中定义了Female这个基本的类型,装饰者ExternalDecorator是Female的派生类,保证了Doris每次穿衣服后都保持Female的基本属性



c++实现

定义Female基本类型
class Female {
public:
Female()
{
}
virtual ~Female()
{
}
virtual std::string getDescription()
{
return desp;
}
virtual double cost()
{
return (double)0.0;
}
virtual int getCharm()
{
return 0;
}
protected:
std::string desp;
};


定义装饰者基本类型
class ExternalDecorator : public Female {
};


现在装饰者和被装饰者都有了,现在定义一个女神的角色
class Goddness : public Female {
public:
Goddness()
{
desp = "I am a FumeBlanc";
}
Goddness(std::string name)
{
desp = "I am " + name;
}
};


给女神来两件衣服,比基尼from维多利亚的秘密,羽绒服fromNIKE
class Bikini : public ExternalDecorator
{
public:
Bikini(Female *female) : female(female)
{
}
virtual std::string getDescription()
{
return female->getDescription() + ", with Bikini of Victoria's secret";
}
virtual double cost()
{
return 500 + female->cost();
}
virtual int getCharm()
{
return female->getCharm() + 100;
}
private:
Female *female;
};

class DownJacket : public ExternalDecorator
{
public:
DownJacket(Female *female) : female(female)
{
}
virtual std::string getDescription()
{
return female->getDescription() + "\nbut with Latest style of NIKE's down jacket";
}
virtual double cost()
{
return 1000 + female->cost();
}
virtual int getCharm()
{
return female->getCharm() - 80;
}
private:
Female *female;
};

简单测试

void DecoratorTest()
{
    Female *doris = new Goddness("Doris");
    ///wear bikini
    Female *doris_bikini = new Bikini(doris);
    ShowFeature(doris_bikini);
    ///wear down-jacket
    Female *doris_downjackt = new DownJacket(doris_bikini);
    ShowFeature(doris_downjackt);
    delete doris_downjackt;
    delete doris_bikini;
    delete doris;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ 设计模式