【HeadFirst 设计模式】装饰者模式的C++实现

一、案例背景

Starbuzz是以扩张速度最快而闻名的咖啡连锁店。如果你在街角看到它的店,在对面街上肯定还会看到另一家。因为扩张速度实在太快了,他们准备更新订单系统,以合乎他们的饮料供应要求。他们原先的类设计是这样的......

购买咖啡时,可以要求在其中加入各种调料,例如:蒸奶(Steamed Milk)、豆浆(Soy)、摩卡(Mocha,也就是巧克力风味)或覆盖奶泡。星巴克会根据所加入的调料收取不同的费用。所以订单系统必须考虑到这些调料部分。这是他们的第一个尝试......

很明显,Starbuzz为自己制造了一个维护噩梦:如果牛奶的价格上扬怎么办?新增一种焦糖调料风味时怎么办?

二、案例分析

看到这么多类时你肯定也会被震惊到......那么问题来了,如何进行改进呢?一个直截了当的解决方案是利用实例变量和继承,就可以追踪这些调料。比如我们在基类中加上实例变量,这些布尔值代表是否加上该调料(牛奶,豆浆,摩卡,奶泡......):

c++ 复制代码
#include <iostream>
#include <string>
using namespace std;

class Beverage
{
private:
    string description {};
    bool   milk {};
    bool   soy {};
    bool   mocha {};
    bool   whip {};

public:
    const string getDiscription()
    {
        return description;
    };
    void setDescription(const string& description)
    {
        this->description = description + "(Add " + (milk ? "Milk " : "") + (soy ? "& Soy " : "") + (mocha ? "& Mocha " : "") + (whip ? "& Whip " : "") + ")";
    }

    virtual const float cost()
    {
        return (milk ? 1 : 0) + (soy ? 2 : 0) + (mocha ? 1 : 0) + (whip ? 1.5 : 0);
    }

    const bool hasMilk() const
    {
        return milk;
    };
    void setMilk(const bool value)
    {
        milk = value;
    };
    const bool hasSoy() const
    {
        return soy;
    };
    void setSoy(const bool value)
    {
        soy = value;
    };
    const bool hasMocha() const
    {
        return mocha;
    };
    void setMocha(const bool value)
    {
        mocha = value;
    };
    const bool hasWhip() const
    {
        return whip;
    };
    void setWhip(const bool value)
    {
        whip = value;
    };
};

class HouseBlend : public Beverage
{
public:
    HouseBlend()
    {
        setMilk(true);
        setSoy(true);
        setDescription("House Blend");
    }
    const float cost() override
    {
        return 5.0 + Beverage::cost();
    }
};

class DarkRoast : public Beverage
{
public:
    DarkRoast()
    {
        setMilk(true);
        setWhip(true);
        setDescription("DarkRoast");
    }
    const float cost() override
    {
        return 8.0 + Beverage::cost();
    }
};

class Decaf : public Beverage
{
public:
    Decaf()
    {
        setMilk(true);
        setWhip(true);
        setSoy(true);
        setDescription("Decaf");
    }
    const float cost() override
    {
        return 10.0 + Beverage::cost();
    }
};

int main()
{
    cout << "我点了一杯" + HouseBlend().getDiscription() << ",花了" << HouseBlend().cost() << "元"<<endl;
    cout << "我点了一杯" + DarkRoast().getDiscription() << ",花了" << DarkRoast().cost() << "元"<<endl;
    cout << "我点了一杯" + Decaf().getDiscription() << ",花了" << Decaf().cost() << "元"<<endl;

    return 0;
}

看起来似乎还行。但是如果将来由于原材料上涨某些调料需要上涨价钱怎么办?如果出现了新的调料呢?如果顾客想要双倍摩卡的咖啡呢?

这些变化都需要我们去直接变更源码。

开放关闭原则:类应该对扩展开放,对修改关闭。

我们的目标是允许类容易扩展,在不修改现有代码的情况下,就可以搭配新的行为。这样的设计具有弹性,可以应对改变,可以接收新的功能来应对改变的需求。

让我们来看看使用装饰者模式是怎么解决问题的:


三、代码分析

这里给出相关案例的C++代码实现:

c++ 复制代码
#include <iostream>
#include <string>
using namespace std;

class Beverage
{
protected:
    string description = "unknown Beverage";

public:
    virtual const string getDescription() const
    {
        return description;
    }
    virtual const double cost() const = 0;
};

class CondimentDecorator : public Beverage
{
public:
    virtual const string getDescription() const = 0;
};

class HouseBlend : public Beverage
{
public:
    HouseBlend()
    {
        description = "HouseBlend";
    }

    const double cost() const override
    {
        return 5.00;
    }
};

class DarkRoast : public Beverage
{
public:
    DarkRoast()
    {
        description = "DarkRoast";
    }

    const double cost() const override
    {
        return 8.00;
    }
};

class Decaf : public Beverage
{
public:
    Decaf()
    {
        description = "Decaf";
    }

    const double cost() const override
    {
        return 10.00;
    }
};

class Milk : public CondimentDecorator
{
public:
    Beverage* beverage {};
    Milk(Beverage* beverage)
    {
        this->beverage = beverage;
    }

    const string getDescription() const override
    {
        return beverage->getDescription() + " & Milk";
    }

    const double cost() const override
    {
        return beverage->cost() + 1.0;
    }
};

class Soy : public CondimentDecorator
{
public:
    Beverage* beverage {};
    Soy(Beverage* beverage)
    {
        this->beverage = beverage;
    }

    const string getDescription() const override
    {
        return beverage->getDescription() + " & Soy";
    }

    const double cost() const override
    {
        return beverage->cost() + 2.0;
    }
};

class Mocha : public CondimentDecorator
{
public:
    Beverage* beverage {};
    Mocha(Beverage* beverage)
    {
        this->beverage = beverage;
    }

    const string getDescription() const override
    {
        return beverage->getDescription() + " & Mocha";
    }

    const double cost() const override
    {
        return beverage->cost() + 2.0;
    }
};

class Whip : public CondimentDecorator
{
public:
    Beverage* beverage {};
    Whip(Beverage* beverage)
    {
        this->beverage = beverage;
    }

    const string getDescription() const override
    {
        return beverage->getDescription() + " & Whip";
    }

    const double cost() const override
    {
        return beverage->cost() + 2.0;
    }
};

int main()
{
    Beverage* houseblend        = new Milk(new Soy(new HouseBlend()));
    Beverage* darkRoast         = new Milk(new Soy(new Whip(new DarkRoast())));
    Beverage* decaf             = new Milk(new Whip(new Decaf()));
    // 双倍摩卡
    Beverage* doubleMochaCoffee = new Milk(new Soy(new Mocha(new Mocha(new HouseBlend()))));

    cout << "我点了一杯" + houseblend->getDescription() << ",花了" << houseblend->cost() << "元" << endl;
    cout << "我点了一杯" + darkRoast->getDescription() << ",花了" << darkRoast->cost() << "元" << endl;
    cout << "我点了一杯" + decaf->getDescription() << ",花了" << decaf->cost() << "元" << endl;
    cout << "我点了一杯" + doubleMochaCoffee->getDescription() << ",花了" << doubleMochaCoffee->cost() << "元" << endl;
    return 0;
}
相关推荐
cpp_25019 分钟前
P1910 L 国的战斗之间谍
数据结构·c++·算法·题解·洛谷·背包dp
txzrxz11 分钟前
c++深度搜索讲解及例题
开发语言·c++·深度搜索·例题讲解
|_⊙14 分钟前
红黑树 (C++)
开发语言·c++·学习
楼田莉子17 分钟前
同步/异步日志系统:工具类以及日志的简单模块
linux·服务器·数据结构·c++
王老师青少年编程17 分钟前
动态规划之【树形DP】第4课:树形DP应用案例实践3
c++·动态规划·dp·树形dp·csp·信奥赛·提高组
七点半77040 分钟前
FFmpeg C++ AI视觉开发核心手册 (整合版)适用场景:视频流接入、AI模型预处理(抽帧/缩放/格式转换)、高性能算法集成。
c++·人工智能·ffmpeg
We་ct41 分钟前
JS手撕:函数进阶 & 设计模式解析
开发语言·前端·javascript·设计模式·面试·前端框架
A.A呐1 小时前
【C++第二十八章】单例模式
c++·单例模式
玖釉-1 小时前
C++ 硬核剖析:if 语句中的“双竖杠” || 到底怎么运行的?
开发语言·c++
m0_716765231 小时前
数据结构三要素、时间复杂度计算详解
开发语言·数据结构·c++·经验分享·笔记·算法·visual studio