蜗牛的家
男儿当自强
posts - 48,  comments - 21,  trackbacks - 0
意图:
动态的给一个对象添加一些额外的职责。比生成子类更为灵活
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;
}
posted on 2008-08-18 22:45 黑色天使 阅读(411) 评论(0)  编辑 收藏 引用 所属分类: 设计模式

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理



<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

常用链接

留言簿(2)

随笔分类

随笔档案

文章档案

搜索

  •  

最新评论

阅读排行榜

评论排行榜