c10.h
#include <string>
class Beverage {
public:
virtual std::string getDescription() = 0;
virtual double cost() = 0;
};
class Soy: public Beverage {
private:
Beverage* beverage; // 把传进来的被装饰者赋给它,以便调用被装饰者的函数
public:
Soy(Beverage* beverage); // 构造对象时传进被装饰者
double cost();
std::string getDescription();
};
class Mocha: public Beverage {
private:
Beverage* beverage;
public:
Mocha(Beverage* beverage);
double cost();
std::string getDescription();
};
class Milk: public Beverage {
private:
Beverage* beverage;
Milk(Beverage* beverage);
double cost();
std::string getDescription();
};
class Beverage1: public Beverage {
public:
std::string getDescription();
double cost();
};
c10.cc
#include "c10.h"
#include <string>
#include <stdio.h>
std::string Soy::getDescription() {
return beverage->getDescription() += "Soy";
}
double Soy::cost() {
return beverage->cost() + 10.5;
}
Soy::Soy(Beverage* beverage) {
this->beverage = beverage;
}
std::string Mocha::getDescription() {
return beverage->getDescription() += "Mocha";
}
double Mocha::cost() {
return beverage->cost() + 20.5;
}
Mocha::Mocha(Beverage* beverage) {
this->beverage = beverage;
}
std::string Beverage1::getDescription() {
return "beverage1";
}
double Beverage1::cost() {
return 10;
}
Milk::Milk(Beverage* beverage) {
this->beverage = beverage;
}
std::string Milk::getDescription() {
return beverage->getDescription() += "Milk";
}
double Milk::cost() {
return 5.1;
}
int main() {
Beverage* b1 = new Beverage1;
b1 = new Soy(b1);
b1 = new Mocha(b1);
printf("%s is $%0.1f\n", (b1->getDescription()).c_str(), b1->cost());
return 0;
}
据说JAVA的IO库有多得使人眼花缭乱的类就是因为使用了这个模式,让你可以一个一个功能的叠加上去。以前一开始接触编程的时候除C外就是看JAVA,当看到有如此多的类和函数且名字又是如此相似的时候确实困惑了,有必要为了加那么一点功能来实现多一个类么!!