码迷,mamicode.com
首页 > 其他好文 > 详细

装饰者模式

时间:2015-08-26 17:47:21      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:

装饰者模式:动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。

技术分享

技术分享
#ifndef BEVERAGE_H
#define BEVERAGE_H

#include <string>

using namespace std;

class Beverage
{
public:
    Beverage(string s):description(s)
    {
    }
    Beverage(){}
    virtual string getDescription()
    {
        return description;
    }
    virtual double cost() = 0;
protected:
    string description;
};

#endif
Beverage.h
技术分享
#ifndef DARKROAST_H
#define DARKROAST_H

#include "Beverage.h"

class DarkRoast : public Beverage
{
public:
    DarkRoast ():Beverage("DarkRoast")
    {}
    double cost()
    {
        return 30;
    }
};

#endif
DarkRoast.h
技术分享
#ifndef DECAF_H
#define DECAF_H

#include "Beverage.h"

class Decaf : public Beverage
{
public:
    Decaf() : Beverage("Decaf")
    {}
    double cost()
    {
        return 50;
    }
};

#endif
Decaf.h
技术分享
#ifndef ESPRESSO_H
#define ESPRESSO_H

#include "Beverage.h"

class Espresso : public Beverage
{
public:
    Espresso() : Beverage("Espresso")
    {}
    double cost()
    {
        return 40;
    }
};

#endif
Espresso.h
技术分享
#ifndef HOUSEBLEND_H
#define HOUSEBLEND_H

#include "Beverage.h"

class HouseBlend : public Beverage
{
public:
    HouseBlend():Beverage("HouseBlend")
    {}
    double cost()
    {
        return 20;
    }
};

#endif
Houseblend.h
技术分享
#ifndef CONDIMENTDECORATOR_H
#define CONDIMENTDECORATOR_H

#include "Beverage.h"

class CondimentDecorator : public Beverage
{
public:
    virtual string getDescription() = 0;
};

#endif
CondimentDecorator.h
技术分享
#ifndef MILK_H
#define MILK_H

#include "CondimentDecorator.h"
#include "Beverage.h"

class Milk : public CondimentDecorator
{
private:
    Beverage* beverage;
public:
    Milk( Beverage* b )
    {
        beverage = b;
    }
    Milk(){}
    virtual ~Milk()
    {
        if (NULL!=beverage)
        {
            delete beverage;
            beverage = NULL;
        }        
    }
    double cost ()
    {
        return beverage->cost() + 0.1;
    }
    string getDescription()
    {
        return beverage->getDescription() + "," + "Milk";
    }
};

#endif
Milk.h
技术分享
#ifndef MOCHA_H
#define MOCHA_H

#include "CondimentDecorator.h"
#include "Beverage.h"

class Mocha : public CondimentDecorator
{
private:
    Beverage* beverage;
public:
    Mocha( Beverage* b )
    {
        beverage = b;
    }
    Mocha(){}
    virtual ~Mocha()
    {
        if (NULL != beverage)
        {
            delete beverage;
            beverage = NULL;
        }        
    }
    double cost ()
    {
        return beverage->cost() + 0.2;
    }
    string getDescription()
    {
        return beverage->getDescription() + "," + "Mocha";
    }
};

#endif
Mocha.h

 

装饰者模式

标签:

原文地址:http://www.cnblogs.com/lisiyuannnn/p/4760755.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!