C++设计模式-Decorator

意图:
动态的给一个对象添加一些额外的职责。比生成子类更为灵活
UML结构图:

适用:
在不影响其他对象的情况下,以动态,透明的方式给单个对象添加职责
处理那些不可撤消的职责
当不能采用生成子类的方式进行扩充时
// test.h
/**/ //
class  Component
{
public:
    Component()
{}
    
virtual ~Component(){}

    
//纯虚函数
    virtual void Operation() = 0;
}
;

// 抽象基类,维护一个指向Component对象的指针
class  Decorator :  public  Component
{
public:
    Decorator(Component
* pComponent) : m_pComponent(pComponent){}
    
virtual ~Decorator();
protected:
    Component
* m_pComponent;
}
;

// 派生自Component,需要给他动态添加职责
class  ConCreateComponent :  public  Component
{
public:
    ConCreateComponent()
{}
    
virtual ~ConCreateComponent(){}

    
virtual void Operation();
}
;

// 派生自Decorator,为ConCreateComponent动态添加职责
class  ConCreateDecorator :  public  Decorator
{
public:
    ConCreateDecorator(Component
* pComponent) : Decorator(pComponent){}
    
virtual ~ConCreateDecorator(){}

    
virtual void Operation();
private:
    
void AddedBehavior(); //动态添加的职责
}
;

// test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include 
< iostream >
#include "test.h"

//
Decorator::~Decorator()
{
    delete m_pComponent;
    m_pComponent = NULL;
}
void ConCreateComponent::Operation()
{
    std::cout 
< < "Operation  of ConCreateComponent\n";
}
void ConCreateDecorator::Operation()
{
    m_pComponent-
> Operation();
    AddedBehavior();
}
void ConCreateDecorator::AddedBehavior()
{
    std::cout 
< < "AddedBehavior  of ConCreateDecorator\n";
}
//
int main(int argc, char* argv[])
{
    Component* Pcomponent 
= new  ConCreateComponent;
    //用这个对象去初始化一个Decorator对象
    //通过多态调用动态添加了职责
    Decorator* pDecorator 
= new  ConCreateDecorator(Pcomponent);
    pDecorator-
> Operation();
    
    delete pDecorator;

    system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值