《大话设计模式》读书笔记之C++实现--chapter6装饰模式
发布时间
阅读量:
阅读量
1、UML类图

2、UML类图详解
装饰模式的结构主要有四个元素:
--抽象组件:Component
--具体组件:ConcreteComponent
--抽象装饰组件:Decorator
--具体装饰组件:ConcreteDecorator
装饰模式的三个主要特点为:
--具体组件和装饰组件都继承于抽象组件
--装饰组件有抽象组件的指针或引用(Component*)
--使用装饰组件和具体组件可以创造出新的类
3、使用场合
一种通过动态增加现有功能的方式,在这种情况下新增的功能仅用于满足某些特定情况下才会触发的独特行为需求;这样做会增加原有类别的复杂性。装饰模式将每个需被修饰的功能独立封装到单独的类别中,并赋予该类别处理修饰相关事务的能力;因此,在运行时若需触发特定行为时(客户代码),可以根据需求选择性地调用相应的修饰功能包装对象;这样能够有效地将类的核心职责与附加修饰分离化;同时能够去除原有类别中重复实现相同修饰逻辑的问题。
用形象化的语言理解装饰模式就是将抽象组件比作一个虚拟角色(如小明),具体组件则可以视为附加在他身上的一系列外在装备(如衬衣、西装、皮鞋和领带),这些装备都是通过可扩展的类实现的。同时必须保证核心虚拟角色始终不变以满足依赖倒置原则——即对外开放但对内封闭的设计理念。这种模式特别适用于需要保持核心功能不变但希望能够灵活添加或选择性调用装饰功能的情况。以下示例程序的具体执行流程如图所示:
4、C+代码实现

#include<iostream>
#include<string>
using namespace std;
//根据UML类图创建的装饰模式的类
class Component {
public:
virtual void operation() = 0;
};
class ConcreteComponent :public Component {
public:
virtual void operation()
{
cout << "I'm no decorator ConcreteComponent" << endl;
}
};
class Decorator :public Component {
public:
Decorator(Component* pComponent) :m_pComponent(pComponent) {}
virtual void operation()
{
if (m_pComponent != NULL)
m_pComponent->operation();
}
protected:
Component* m_pComponent;
};
class ConcreteDecoratorA :public Decorator {
public:
ConcreteDecoratorA(Component *pDecorator) : Decorator(pDecorator) {}
virtual void operation()
{
Addoperation();
Decorator::operation();
}
void Addoperation()
{
cout << "I'm add operationA" << endl;
}
};
class ConcreteDecoratorB :public Decorator {
public:
ConcreteDecoratorB(Component *pDecorator) : Decorator(pDecorator) {}
virtual void operation()
{
Addoperation();
Decorator::operation();
}
void Addoperation()
{
cout << "I'm add operationB" << endl;
}
};
//主程序
int main()
{
Component *pComponentObj = new ConcreteComponent();
Decorator *pDecoratorAOjb = new ConcreteDecoratorA(pComponentObj);
pDecoratorAOjb->operation();
cout << "=============================================" << endl;
Decorator *pDecoratorBOjb = new ConcreteDecoratorB(pComponentObj);
pDecoratorBOjb->operation();
cout << "=============================================" << endl;
Decorator *pDecoratorBAOjb = new ConcreteDecoratorB(pDecoratorAOjb);
pDecoratorBAOjb->operation();
cout << "=============================================" << endl;
delete pDecoratorBAOjb;
pDecoratorBAOjb = NULL;
delete pDecoratorBOjb;
pDecoratorBOjb = NULL;
delete pDecoratorAOjb;
pDecoratorAOjb = NULL;
delete pComponentObj;
pComponentObj = NULL;
system("pause");
return 0;
}
全部评论 (0)
还没有任何评论哟~
