(三)装饰模式

见注释:

// test.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <string>
#include <iostream>
#include <memory>//为了应用智能指针
using namespace std;

//装饰模式,动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。

//装饰模式是为已有功能动态添加更多功能的一种方式。

//当系统需要新功能时,是向旧的类中添加新的代码。这些新加的代码通常装饰了原有类的核心职责
//或主要行为。
//?
//他把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此当需要执行特殊行为时,
// 客户端代码就可以再运行时根据需要有选择的、按顺序的使用装饰功能包装的对象了。
// 有效地把类的核心职责和装饰功能区分开了。而且可以去除相关类中重复的装饰逻辑。

class Coffee
{
public:
    Coffee() : m_price(1.0)
    {
        cout << "Coffee Constructor..." << endl; 

    }

    virtual ~Coffee()
    {
        cout << "Coffee DisConstructor..." << endl; 
    }

    //咖啡有计算价格方法
    virtual double cost()
    {
        return m_price;
    }

private:
    double m_price;
};

class Decorator : public Coffee
{
public:
    Decorator()
    {
        cout << "Decorator Constructor..." << endl; 
    }
    virtual ~Decorator()
    {
        cout << "Decorator DisConstructor..." << endl; 
    }
public:
    shared_ptr<Coffee> m_f;//一个具体的咖啡对象
};

//加牛奶装饰类
class AddMilk : public Decorator
{
public:
    ~AddMilk()
    {
        cout << "AddMilk DisConstructor..." << endl; 
    }

    //咖啡类型的对象进行装饰
    AddMilk(shared_ptr<Coffee> f)
    {
        cout << "AddMilk Constructor..." << endl;

        m_f = f;
    }

    //加牛奶的价格计算方式
    double cost()
    {
        return 2.5 + m_f->cost(); 
    }
};

//加糖装饰类
class AddSuger : public Decorator
{
public:
    ~AddSuger()
    {
        cout << "AddSuger DisConstructor..." << endl; 
    }

    //咖啡类型的对象进行装饰
    AddSuger(shared_ptr<Coffee> f)
    {
        cout << "AddSuger Constructor..." << endl; 

        m_f = f;
    }

    //加糖的价格计算方式
    double cost()
    {
        return 1.5 + m_f->cost(); 
    }	
};

int _tmain(int argc, _TCHAR* argv[])
{
    //对原味咖啡对象进行装饰,先加牛奶后加糖
    shared_ptr<Coffee> coffee(new AddSuger(shared_ptr<Coffee>(new AddMilk(shared_ptr<Coffee>(new Coffee())))));

    //这样咖啡的价格就被附加。
    cout << coffee->cost() << endl;

    //计算下集成体系下的内存大小
    cout <<  "Size :" << sizeof(*coffee) << endl;

	return 0;
}

输出:

Coffee Constructor...
Coffee Constructor...
Decorator Constructor...
AddMilk Constructor...
Coffee Constructor...
Decorator Constructor...
AddSuger Constructor...
5
Size :16
AddSuger DisConstructor...
Decorator DisConstructor...
AddMilk DisConstructor...
Decorator DisConstructor...
Coffee DisConstructor...
Coffee DisConstructor...
Coffee DisConstructor...
请按任意键继续. . .

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值