c++-装饰者模式三

c++ 装饰者模式一
c++ 装饰者模式二
前面的两个文章将的是通过虚函数这种动多态实现的装饰者模式
本文将一种基于模板的装饰者模式

具体如下
Beverage<Espresso, Mocha, Mocha, Whip, Sugar> ss

#include <iostream>
#include <string>
#include <memory>

using namespace std;

string doubleToStr(double price) {
    char buffer[128];
    snprintf(buffer, sizeof(buffer), "%.2lf", price);
    return buffer;
}

string descriptionFormat(const string &name, double price, const string &suffix = "with") {
    string ans = suffix;
    if (!suffix.empty()) {
        ans += " ";
    }
    return ans + name + "(" + doubleToStr(price) + ")\n";
}

// 添加料
class Mocha {
 public:
    string getDescription() const {
        return descriptionFormat("Mocha", cost());
    }

    double cost() const {
        return .32;
    }
};

class Whip {
 public:
    string getDescription() const {
        return descriptionFormat("Whip", cost());
    }

    double cost() const {
        return .23;
    }
};

class Sugar {
 public:
    string getDescription() const {
        return descriptionFormat("Sugar", cost());
    }

    double cost() const {
        return .1;
    }
};

// 饮品
class Espresso {
 public:
    string getDescription() const {
        return descriptionFormat("Espresso", cost(), "");
    }

    double cost() const {
        return 1.99;
    }
};

template<typename T>
string getDescription(const T &t) {
    return t.getDescription();
}

template<size_t ... Index, typename ...Decorator>
string make_description(index_sequence<Index...>, const tuple<Decorator...> &data) {
    return (getDescription(get<Index>(data)) + ...);
}

template<typename ...Decorator>
string make_description(index_sequence<>, const tuple<Decorator...> &data) {
    return "";
}

template<typename T>
double cost(const T &t) {
    return t.cost();
}


template<size_t ... Index, typename ...Decorator>
double make_total_cost(index_sequence<Index...>, const tuple<Decorator...> &data) {
    return (cost(get<Index>(data)) + ...);
}

template<typename ...Decorator>
double make_total_cost(index_sequence<>, const tuple<Decorator...> &data) {
    return 0;
}

template<typename ...Decorator>
class Beverage : public tuple<Decorator...> {
 public:
    constexpr static auto type_count = sizeof ...(Decorator);
    using index_seq = make_index_sequence<type_count>;

    string getDescription() const {
        return make_description(index_seq{}, *this);
    }

    double totalCost() const {
        return make_total_cost(index_seq{}, *this);
    }
};

int main() {
    Beverage<Espresso, Mocha, Mocha, Whip, Sugar> ss;
    cout << "详情:\n" << ss.getDescription() << endl;
    cout << "账单合计: " << ss.totalCost() << endl;
    cout << endl;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值