装饰模式(Decorate Pattern)
- 描述:动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的代替方案
- 注意:装饰者和被装饰者必须是一样的类型
- 缺点:利用装饰着模式,常常造成设计中有大量的小类,可能会造成使用此API程序员的困扰
- 代码举例:
class Beverage
{
public:
virtual std::string getDescription();
virtual float cost();
}
class DarkRoast : public Beverage
{
public:
virtual std::string getDescription()
{ return "DarkRoast";}
virtual float cost()
{ return 1.0; }
}
class CondimentDecorator : public Beverage
{
public:
CondimentDecorator(Beverage* pBeverage);
virtual std::string getDescription();
virtual float cost();
Beverage* m_pBeverage;
}
class Milk : public CondimentDecorator
{
public:
Milk(Beverage* pBeverage):CondimentDecorator(pBeverage)
{ }
std::string getDescription()
{ return m_pBeverage->getDescription() + "Milk"; }
float cost()
{ return m_pBeverage->cost() + 0.5; }
}
int main()
{
Beverage* beverage = new DarkRoast();
beverage = new Milk(beverage);
beverage->getDescription();//"DarkRost + Milk"
beverage->cost();//1.5
}
来源:CSDN
作者:冻融
链接:https://blog.csdn.net/wwhx27/article/details/104113532