《Head First设计模式》之装饰者模式实例代码C++实现

书中实例用java编写,由于本人不能熟练使用java,所以用c++实现以达到练习效果,代码如下:

#include <iostream>
using namespace std;
#include <string>

class Beverage {
public:
	Beverage(string desc = "") : description(desc) { }
	virtual string getDescription() const { return description; }
	virtual double cost() = 0;
private:
	string description;
};

class Condiment : public Beverage {
public:
	string getDescription() const { 
		return "";
	}
};

class Espresso : public Beverage {
public:
	Espresso() {
		this->description = "Espresso";
	}
	string getDescription() const {
		return "Espress";
	}
	double cost() {
		return 1.99;
	}
private:
	string description;
};

class HouseBlend : public Beverage {
public:
	HouseBlend() {
		this->description = "House Blend";
	}
	string getDescription() const {
		return "House Blend";
	}
	double cost() {
		return 0.89;
	}
private:
	string description;
};

class DarkRoast : public Beverage {
public:
	DarkRoast() {
		this->description = "Dark Roast";
	}
	string getDescription() const {
		return "Dark Roast";
	}
	double cost() {
		return 0.59;
	}
private:
	string description;
};

class Decat : public Beverage {
public:
	Decat() {
		this->description = "Decat";
	}
	string getDescription() const {
		return "Decat";
	}
	double cost() {
		return 0.69;
	}
private:
	string description;
};

class Mocha : public Condiment {
public:
	Mocha(Beverage* b) : beverage(b) { }
	string getDescription() const {
		return beverage->getDescription() + ",Mocha";
	}
	double cost() {
		return 0.2 + beverage->cost();
	}
private:
	Beverage* beverage;
};

class Soy : public Condiment {
public:
	Soy(Beverage* b) : beverage(b) { }
	string getDescription() const {
		return beverage->getDescription() + ",Soy";
	}
	double cost() {
		return 0.3 + beverage->cost();
	}
private:
	Beverage *beverage;
};

int main()
{
	Beverage *b1 = new DarkRoast();
	b1 = new Mocha(b1);
	b1 = new Mocha(b1);
	cout << "description: " << b1->getDescription() << endl;;
	cout << "cost: $" << b1->cost() << endl;

	cout << "-----------------------" << endl;

	Beverage *b2 = new HouseBlend();
	b2 = new Soy(b2);
	b2 = new Mocha(b2);
	cout << "description: " << b2->getDescription() << endl;;
	cout << "cost: $" << b2->cost() << endl;	
}


输出结果如下:

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值