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;
}