装饰者模式:动态的将责任附加到对象上。
C++示例代码如下:
/*
* CONTENTS: DESIGN PATTERN, DECORATOR PATTERN
* AUTHOR: YAO H. WANG
* TIME: 2013-10-19 22:13:19
* EDITION: 1
*
* ALL RIGHTS RESERVED!
*/
#include <string>
#include <iostream>
using namespace std;
//类
class Beverage
{
public:
string description;
virtual string getDescription()
{
return description;
}
virtual double cost() = 0;
};
//装饰类
class CondimentDecorator: public Beverage
{
public:
Beverage *beverage;
virtual string getDescription() = 0;
};
//具体类
class Espresso: public Beverage
{
public:
Espresso()
{
description = "Espresso";
}
double cost()
{
return 1.99;
}
};
class HouseBlend: public Beverage
{
public:
HouseBlend()
{
description = "HouseBlend";
}
double cost()
{
return .89;
}
};
class DarkRoast: public Beverage
{
public:
DarkRoast()
{
description = "DarkRoast";
}
double cost()
{
return .99;
}
};
//具体装饰类
class Mocha: public CondimentDecorator
{
public:
Mocha(Beverage *beverage)
{
CondimentDecorator::beverage = beverage;
}
string getDescription()
{
return beverage->getDescription() + ", Mocha";
}
double cost()
{
return .20 + beverage->cost();
}
};
class Whip: public CondimentDecorator
{
public:
Whip(Beverage *beverage)
{
CondimentDecorator::beverage = beverage;
}
string getDescription()
{
return beverage->getDescription() + ", Whip";
}
double cost()
{
return .10 + beverage->cost();
}
};
class Soy: public CondimentDecorator
{
public:
Soy(Beverage *beverage)
{
CondimentDecorator::beverage = beverage;
}
string getDescription()
{
return beverage->getDescription() + ", Soy";
}
double cost()
{
return .15 + beverage->cost();
}
};
//测试
void main()
{
Beverage *beverage = new Espresso();
cout << beverage->getDescription() << " $" << beverage->cost() << endl;
Beverage *beverage2 = new DarkRoast();
beverage2 = new Mocha(beverage2);
beverage2 = new Mocha(beverage2);
beverage2 = new Whip(beverage2);
cout << beverage2->getDescription() << " $" << beverage2->cost() << endl;
Beverage *beverage3 = new HouseBlend();
beverage3 = new Soy(beverage3);
beverage3 = new Mocha(beverage3);
beverage3 = new Whip(beverage3);
cout << beverage3->getDescription() << " $" << beverage3->cost() << endl;
delete beverage;
delete beverage2;
delete beverage3;
}