// 设计模式测试.cpp : 定义控制台应用程序的入口点。
// 装饰器模式
#include "stdafx.h"
#include <string>
#include <iostream>
#include <vector>
#include <list>
using namespace std;
/*********************装饰者模式之饮料示例*************************************/
//饮料抽象基类
class Beverage
{
protected:
string description = "Unknown Beverage";
public:
virtual string getDescription() {
return description;
}
virtual double cost()= 0;
};
class FirstBeverage : public Beverage
{
public:
FirstBeverage() {
description = "First Beverage";
}
double cost() {
return 1.99;
}
};
class SecondBeverage : public Beverage
{
public:
SecondBeverage() {
description = "Second Beverage";
}
double cost() {
return 0.99;
}
};
//调料基类/装饰者类
class CondimentDecorator : public Beverage
{
public:
virtual string getDescription() = 0;
};
class Salt : public CondimentDecorator
{
Beverage *beverage;
public:
Salt(Beverage *b) {
beverage = b;
}
string getDescription() {
return beverage->getDescription() + " ,Salt";
}
double cost() {
return beverage->cost() + .2;
}
};
class Suger : public CondimentDecorator
{
Beverage *beverage;
public:
Suger(Beverage *b) {
beverage = b;
}
string getDescription() {
return beverage->getDescription() + " ,Suger";
}
double cost() {
return beverage->cost() + .3;
}
};
//主函数
int main()
{
Beverage *beverage1 = new FirstBeverage();
cout << beverage1->getDescription() << " $" << beverage1->cost()<<endl;
Beverage *beverage2 = new SecondBeverage();
beverage2 = new Salt(beverage2);
beverage2 = new Suger(beverage2);
cout << beverage2->getDescription() << " $" << beverage2->cost() << endl;
system("Pause");
return 0;
}
C++:设计模式之装饰器模式(例子)
最新推荐文章于 2024-06-14 02:53:51 发布