蜗牛的家
男儿当自强
posts - 48,  comments - 21,  trackbacks - 0
意图:
使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系,将这些对象连成一条链,并沿着这条链传递请求,直到有一个对象处理它为止
UML图:

适用:
有多个的对象可以处理一个请求,哪个对象处理该请求运行时刻自动确定
你想在不明确指定接收者的情况下,向多个对象汇总的一个提交请求
可处理一个请求的对象结合应被动态指定
//test.h
//////////////////////////////////////////////////////////////////////////
class Handler
{
public:
    Handler(Handler *pSuccessor = NULL);
    virtual ~Handler();
    
    virtual void HandlerRequest() = 0;
protected:
    Handler* m_pSuccessor;
};

class ConCreateHandle1 : public Handler
{
public:
    ConCreateHandle1(Handler *pSuccessor = NULL) : Handler(pSuccessor){}
    virtual ~ConCreateHandle1(){}
    
    virtual void HandlerRequest();
};

class ConCreateHandle2 : public Handler
{
public:
    ConCreateHandle2(Handler *pSuccessor = NULL) : Handler(pSuccessor){}
    virtual ~ConCreateHandle2(){}

    virtual void HandlerRequest();
};

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

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

using namespace std;
//////////////////////////////////////////////////////////////////////////
Handler::Handler(Handler *pSuccessor /* = NULL */) : m_pSuccessor(pSuccessor)
{
}

Handler::~Handler()
{
    delete m_pSuccessor;
    m_pSuccessor = NULL;
}

void ConCreateHandle1::HandlerRequest()
{
    if (NULL != m_pSuccessor)
    {
        m_pSuccessor->HandlerRequest();
    }
    else
    {
        cout 
<< "HandlerRequest by ConCreateHandle1\n";
    }
}

void ConCreateHandle2::HandlerRequest()
{
    // 如果m_pSuccessor被初始化了就调用他的接口,负责调用自己的接口
    if (NULL !
= m_pSuccessor)
    
{
        m_pSuccessor-
>HandlerRequest();
    }
    else
    {
        cout 
<< "HandlerRequest by ConCreateHandle2\n";
    }
}
//////////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[])
{
    Handler *p1 
= new ConCreateHandle1;
    Handler *p2 
= new ConCreateHandle2(p1);
    
    p2-
>HandlerRequest();
    
    delete p2;
    
    system("pause");
    return 0;
}

posted on 2008-08-19 23:27 黑色天使 阅读(304) 评论(0)  编辑 收藏 引用 所属分类: 设计模式

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



<2008年8月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456

常用链接

留言簿(2)

随笔分类

随笔档案

文章档案

搜索

  •  

最新评论

阅读排行榜

评论排行榜