您的位置:首页 > 其它

(三)装饰模式

2015-09-15 18:08 204 查看
见注释:

// 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...

请按任意键继续. . .
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: