Head first design patterns c++实现, decorator

//beverage.h    component

#ifndef BEVERAGE_H__
#define BEVERAGE_H__

#include <string>

class Beverage {
public:
 Beverage():description("Unknown beverage"),cost(0){}
 virtual double Cost() = 0;
 virtual std::string GetDescription() = 0;

private:
 double cost;
 std::string description;
 Beverage(const Beverage&);
 Beverage& operator=(const Beverage&);
};

#endif 

//concimentdec.h    decorator

#ifndef CONDIMENTDOC_H__
#define CONDIMENTDOC_H__

#include "Beverage.h"

class CondimentDecorator : virtual public Beverage {
public:
 CondimentDecorator(){}
private:
 CondimentDecorator(const CondimentDecorator&);
 CondimentDecorator& operator=(const CondimentDecorator&);
};

#endif

//houseblend.h    concrete component

#ifndef HOUSEBLEND_H__
#define HOUSEBLEND_H__

#include "Beverage.h"
#include <string>

class HouseBlend : virtual public Beverage {
public:
 HouseBlend():Beverage("This is a House Blend Coffee", 2.2){}
 double Cost() { return cost; };

private:
 HouseBlend(const HouseBlend& );
 HouseBlend& operator=(const HouseBlend&);
};

#endif

//milk.h concrete decorator

#ifndef MILK_H__
#define MILK_H__

#include "CondimentDec.h"
#include <string>

class MilkDecorator : virtual public CondimentDecorator {
public:
 MilkDecorator(Beverage* bev):beverage(bev){}
 double Cost() { return beverage->Cost() + 0.7; }
 std::string GetDescription() { return beverage->GetDescription() + " with Milk"; }

private:
 Beverage* beverage;
 MilkDecorator(const MilkDecorator&);
 MilkDecorator& operator=(const MilkDecorator&);
};

#endif

//mocha.h  concrete decorator

#ifndef MOCHA_H__
#define MOCHA_H__

#include "CondimentDec.h"
#include <string>

class MochaDecorator : virtual public CondimentDecorator {
public:
 MochaDecorator(Beverage* bev):beverage(bev){};
 double Cost() { return beverage->Cost() + 0.5; }
 std::string GetDescription() { return beverage->GetDescription() + " with Mocha"; }

private:
 Beverage* beverage;
 MochaDecorator(const MochaDecorator&);
 MochaDecorator& operator=(const MochaDecorator&);
};

#endif

//main.cpp

#include "Mocha.h"
#include "Milk.h"
#include "HouseBlend.h"
#include <iostream>

using namespace std;

int main()
{
 Beverage* hb = new HouseBlend();

 cout << hb->Cost() << "/n";
 cout << hb->GetDescription() << "/n";

 hb = new MochaDecorator(hb);
 cout << hb->Cost() << "/n";
 cout << hb->GetDescription() << "/n";

 hb = new MilkDecorator(hb);
 cout << hb->Cost() << "/n";
 cout << hb->GetDescription() << "/n";


 return EXIT_SUCCESS;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值