设计模式入门,装饰着模式,c++代码实现
// test03.cpp : Defines the entry point for the console application.
//
//设计模式第3章 装饰者模式
#include "stdafx.h"
#include <string>
#include <iostream>
//#include <cstring>
using namespace std;
class Beverage
{
public:
string description /*= "Unkown Beverage"*/;//只有静态整型常量数据成员能在类中初始化
public:
virtual string getDescription()//必须为虚函数
{
return description;
}
virtual double cost(){return 0;} ;//必须为虚函数
};
class CondimentDecorator : public Beverage
{
virtual string getDescription(){return NULL;} ;
};
class Espresso : public Beverage
{
public:
Espresso()
{
description = "Espresso";
}
double cost(){
return 1.99;
}
};
class HouseBlend : public Beverage
{
public:
HouseBlend()
{
description = "House Blend Coffee";
}
double cost()
{
return .89;
}
};
class DarkRoast : public Beverage
{
public:
DarkRoast()
{
description = "Dark Roast Coffee";
}
double cost()
{
return .99;
}
};
class Mocha : public CondimentDecorator
{
Beverage* beverage;
public:
Mocha(Beverage* beverage)//必须为指针
{
this->beverage = beverage;
}
string getDescription()
{
return beverage->getDescription() + ", Mocha";
}
double cost()
{
return .20 + beverage->cost();
}
};
class Whip : public CondimentDecorator
{
Beverage* beverage;
public:
Whip(Beverage* beverage)
{
this->beverage = beverage;
}
string getDescription()
{
return beverage->getDescription() + ", Whip";
}
double cost()
{
return .10 + beverage->cost();
}
};
class Soy : public CondimentDecorator
{
Beverage* beverage;
public:
Soy(Beverage* beverage)
{
this->beverage = beverage;
}
string getDescription()
{
return beverage->getDescription() + ", Soy";
}
double cost()
{
return .15 + beverage->cost();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Beverage* beverage = new Espresso();
cout<<beverage->getDescription() << " $ " << beverage->cost()<<endl;
Beverage* beverage2 = new DarkRoast();
beverage2 = new Mocha(beverage2);//必须传递指针
beverage2 = new Mocha(beverage2);
beverage2 = new Whip(beverage2);
//printf("%s %$ %f",beverage2->getDescription(),beverage2->cost());//printf 不能输出string类型
cout<<beverage2->getDescription()<<" $ "<<beverage2->cost()<<endl;
Beverage* beverage3 = new HouseBlend();
beverage3 = new Soy(beverage3);
beverage3 = new Mocha(beverage3);
beverage3 = new Whip(beverage3);
//printf("%s %$ %f",beverage3->getDescription(),beverage3->cost());
cout<<beverage3->getDescription()<<" $ "<<beverage3->cost()<<endl;
return 0;
}