您的位置:首页 > 其它

设计模式之装饰者模式

2008-11-14 13:35 288 查看
#include <iostream>

#include <string>

using namespace std;

// 组件接口类

class Component

{

public:

// 默认构造函数

Component(){}

// 析构造函数

virtual ~Component(){}

// 返回组件描述

virtual const string GetDescription() const = 0;

// 绘制组件

virtual void Draw() const = 0;

};

// 一般组件抽象类

class ConmmonComponent:public Component

{

private:

string m_strDescription;

public:

// 带参数构造函数

ConmmonComponent(const string &p_strDescription):Component(),m_strDescription(p_strDescription){}

// 返回组件描述

virtual const string GetDescription() const

{

return ("It is a " + m_strDescription);

}

};

// 文本视图组件

class TextViewComponent:public ConmmonComponent

{

public:

// 带参数构造函数

TextViewComponent(const string &p_strDescription):ConmmonComponent(p_strDescription){}

// 绘制组件

virtual void Draw() const

{

cout << "Now let's draw the textview." << endl;

}

};

// 装饰者抽象类

class Decorator:public Component

{

private:

Component *m_pComponent; // 被装饰者

public:

// 带参数构造函数

Decorator(Component *p_pComponent):m_pComponent(p_pComponent){}

//------------

// 委托

//------------

// 返回组件描述

virtual const string GetDescription() const

{

return m_pComponent->GetDescription();

}

// 绘制组件

virtual void Draw() const

{

m_pComponent->Draw();

}

};

// 滚动条装饰者

class ScollDecorator:public Decorator

{

public:

// 默认构造函数

ScollDecorator(Component *p_pComponent):Decorator(p_pComponent){}

// 返回组件描述

virtual const string GetDescription() const

{

return (Decorator::GetDescription() + " with a scoll");

}

// 绘制组件

virtual void Draw() const

{

cout << "Now let's draw the scoll." << endl;

Decorator::Draw();

}

};

// 边框装饰者

class BorderDecorator:public Decorator

{

public:

// 默认构造函数

BorderDecorator(Component *p_pComponent):Decorator(p_pComponent){}

// 返回组件描述

virtual const string GetDescription() const

{

return (Decorator::GetDescription() + " and a border.");

}

// 绘制组件

virtual void Draw() const

{

cout << "Now let's draw the border." << endl;

Decorator::Draw();

}

};

int main()

{

TextViewComponent textComponent("textview");

ScollDecorator scollDecorator(&textComponent);

BorderDecorator borderDecorator(&scollDecorator);

cout << borderDecorator.GetDescription() << endl;

borderDecorator.Draw();

system("pause");

return 0;

}

个人对装饰者模式的理解:当我们想要为某个组件对象添加新功能时,和采用继承这种僵化的设计方式相比,装饰者模式将带给程序很大的灵活性和可扩展性.针对借口进行编程并在装饰者抽象类的函数,使得对于被装饰组件和客户代码而言装饰者都是透明的.其实装饰模式的设计思想是极度符合人的思考方式:当我们根据已存在的特性创建出整合这些特性的新对象时,继承设计方式必然严重依赖于现存的类,而如果将每个特性进行独立打散,则可以动态的组合出我们需要的类型.就是使用不同颜色的方块进行搭基木一样,最终的对象组件是积木,而各种特性则对应于各种颜色的方块.在动态地改变对象行为方面,策略模式亦有同样的功能,但它并不能灵活地安排各种行为执行顺序.不过装饰者模式中让装饰者Public继承自组件接口的方式是违反is a原则的,不过这里进行Public继承的主要目的是使装饰者与被装饰组件都派生自相同的接口,以便借用多态的特性使装饰者透明于客户代码.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: