一、工程目录
二、Code
1. Beverage.h
include <string>
using std::string;
class Beverage
{
public:
virtual string getDescription()
{
return description;
}
virtual double cost() = 0;
virtual ~Beverage()
{
description = "Unkonwn Beverage";
}
protected:
string description = "Unkonwn Beverage";
};
2. CondimentDecorator.h
#include "common/Beverage.h"
class CondimentDecorator : public Beverage
{
public:
virtual string getDescription() = 0;
};
3. DarkRoast.h
#include "common/Beverage.h"
class DarkRoast : public Beverage
{
public:
DarkRoast()
{
description = "Dark Roast Coffee";
}
double cost() override
{
return 1.45;
}
};
4. Decat.h
#include "common/Beverage.h"
class Decat : public Beverage
{
public:
Decat()
{
description = "Decat Coffee";
}
double cost() override
{
return 0.98;
}
};
5. Espresso.h
#include "common/Beverage.h"
class Espresso : public Beverage
{
public:
Espresso()
{
description = "Espresso Coffee";
}
double cost() override
{
return 1.99;
}
};
6. HouseBlend.h
#include "common/Beverage.h"
class HouseBlend : public Beverage
{
public:
HouseBlend()
{
description = "House Blend Coffee";
}
double cost() override
{
return 0.89;
}
};
7. Mocha.h
#include "common/CondimentDecorator.h"
class Mocha : public CondimentDecorator
{
public:
Mocha(Beverage* beverage)
{
this->beverage = beverage;
}
string getDescription() override
{
return beverage->getDescription() + ", Mocha";
}
double cost() override
{
return 0.2 + beverage->cost();
}
private:
Beverage* beverage;
};
8. Soy.h
#include "common/CondimentDecorator.h"
class Soy : public CondimentDecorator
{
public:
Soy(Beverage* beverage)
{
this->beverage = beverage;
}
string getDescription() override
{
return beverage->getDescription() + ", Soy";
}
double cost() override
{
return 0.15 + beverage->cost();
}
private:
Beverage* beverage;
};
9. Whip.h
#include "common/CondimentDecorator.h"
class Whip : public CondimentDecorator
{
public:
Whip(Beverage* beverage)
{
this->beverage = beverage;
}
string getDescription() override
{
return beverage->getDescription() + ", Whip";
}
double cost() override
{
return 0.33 + beverage->cost();
}
private:
Beverage* beverage;
};
三、test
1. main.cpp
#include <iostream>
#include "coffee/Espresso.h"
#include "coffee/DarkRoast.h"
#include "decorator/Soy.h"
#include "decorator/Mocha.h"
#include "decorator/Whip.h"
using namespace std;
int main(int argc, char **argv)
{
Beverage* espresso = new Espresso();
cout << espresso->getDescription() << " $" << espresso->cost() << endl;
Beverage* darkRoast = new DarkRoast();
Beverage* soy = new Soy(darkRoast);
Beverage* mocha = new Mocha(soy);
Beverage* whip = new Whip(mocha);
cout << whip->getDescription() << " $" << whip->cost() << endl;
if (espresso) { delete espresso; espresso = nullptr; }
if (darkRoast) { delete darkRoast; darkRoast = nullptr;}
if (soy) { delete soy; soy = nullptr; }
if (mocha) { delete mocha; mocha = nullptr; }
if (whip) { delete whip; whip = nullptr; }
return 0;
}
2. result