Headfirst设计模式的C++实现——装饰者模式(Decorater)

时间:2022-11-01 13:44:07

Beverage.h

 #ifndef BEVERAGE_H_INCLUDED
#define BEVERAGE_H_INCLUDED #include <string> class Beverage
{
public:
Beverage( std::string description = "Unknown Beverage" ) : m_description ( description ) {}
virtual std::string getDescription() { return m_description; }
virtual double cost() = ;
private:
std::string m_description;
}; #endif // BEVERAGE_H_INCLUDED

CondimentDecorator.h

 #ifndef CONDIMENTDECORATOR_H_INCLUDED
#define CONDIMENTDECORATOR_H_INCLUDED #include <string>
#include "Beverage.h" class CondimentDecorator : public Beverage
{
public:
virtual std::string getDescription() = ;
}; #endif // CONDIMENTDECORATOR_H_INCLUDED

HouseBlend.h

 #ifndef HOUSEBLEND_H_INCLUDED
#define HOUSEBLEND_H_INCLUDED #include "Beverage.h" class HouseBlend : public Beverage
{
public:
HouseBlend () : Beverage( "House Blend Coffee" ) {}
double cost() { return .; }
}; #endif // HOUSEBLEND_H_INCLUDED

Mocha.h

 #ifndef MOCHA_H_INCLUDED
#define MOCHA_H_INCLUDED #include "CondimentDecorator.h" class Mocha : public CondimentDecorator
{
public:
Mocha ( Beverage * p_beverage ) : m_p_beverage ( p_beverage ) {}
std::string getDescription() { return m_p_beverage->getDescription() + ", Mocha"; }
double cost() { return . + m_p_beverage->cost(); }
private:
Beverage *m_p_beverage;
}; #endif // MOCHA_H_INCLUDED

main.cpp

 #include <iostream>
#include "HouseBlend.h"
#include "Mocha.h"
int main()
{
HouseBlend house_blend;
std::cout << house_blend.getDescription() << ": " << house_blend.cost() << std::endl; Mocha mocha_house_blend( &house_blend );
std::cout << mocha_house_blend.getDescription() << ": " << mocha_house_blend.cost() << std::endl; Mocha mocha_mocha_house_blend( &mocha_house_blend );
std::cout << mocha_mocha_house_blend.getDescription() << ": " << mocha_mocha_house_blend.cost() << std::endl; return ;
}

一点个人理解:

起初对于为什么Mocha类要从CondimentDecorator类继承也就是CondimentDecorator类存在的意义感到疑惑,并做了一次尝试:跳过CondimentDecorator类,让Mocha类直接从Beverage类继承,发现效果是一样的。那为什么还要有CondimentDecorator类的存在呢?

原书上有这么一段解释:

“所有的调料装饰着都必须重新实现getDescription()方法。稍后我们会解释为什么......”

"我们希望叙述不只是描述饮料,而是完整的连调料都描述出来......"

我推测作者的意思是说通过CondimentDecorator类,并且把getDescription方法设置为纯虚函数就可以强制让所有调料类实现此方法。如果不通过getDescription类,那么调料类就可以不实现此方法从而不符合需求。