您的位置:首页 > 编程语言 > C语言/C++

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

2012-10-15 23:02 826 查看
书中实例用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;
}


输出结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: