设计模式学习-行为模式-职责链模式
来源:互联网 发布:知乎 055驱逐舰 编辑:程序博客网 时间:2024/06/13 03:39
所有的人写模式,都是从创建模式开始,然后是结构模式,然后是行为模式。我想倒而为之。然而所有的模式都是用英文描述的,有时候再换成中文去描述这些模式真的很别扭。我只能尽量的详细的描述每个模式,再配上更多的使用案例,和复杂的案例。
chain of Responsibility:
目的:
可以把请求者与接收处理者分开。而请求的处理对象可能有多个,这样每一个请求都被自动的由一串的接收者处理。当一个对象不处理这个请求时,它会自动传给下一个对象处理。直到有一个对象处理了这个请求,或者所有的处理对象被遍历完全。
request process
Encapsulate the processing elements inside a “pipeline” abstraction
the class diagram:
the example of c++ code:
#include <iostream>
#include <vector>
#include <ctime>
using namespace std;
class Base
{
Base *next; // 1. "next" pointer in the base class
public: Base()
{
next = 0;
}
void setNext(Base *n)
{
next = n;
}
void add(Base *n)
{
if (next)
next->add(n);
else
next = n;
} // 2. The "chain" method in the base class always delegates to the next obj
virtual void handle(int i)
{
next->handle(i);
}
};
class Handler1: public Base
{
public:
/*virtual*/void handle(int i)
{
if (rand() % 3)
{
// 3. Don't handle requests 3 times out of 4
cout << "H1 passsed " << i << " ";
Base::handle(i); // 3. Delegate to the base class
}
else
cout << "H1 handled " << i << " ";
}
};
class Handler2: public Base
{
public:
/*virtual*/void handle(int i)
{
if (rand() % 3)
{
cout << "H2 passsed " << i << " ";
Base::handle(i);
}
else
cout << "H2 handled " << i << " ";
}
};
class Handler3: public Base
{
public:
/*virtual*/void handle(int i)
{
if (rand() % 3)
{
cout << "H3 passsed " << i << " ";
Base::handle(i);
}
else
cout << "H3 handled " << i << " ";
}
};
int main()
{
srand(time(0));
Handler1 root;
Handler2 two;
Handler3 thr;
root.add(&two);
root.add(&thr);
thr.setNext(&root);
for (int i = 1; i < 10; i++)
{
root.handle(i);
cout << '/n';
}
}
上面是一个职责链的一个简单的例子,基类负责把消息传递给下一个对象处理,而子类可以定义自己的消息处理函数,或者不处理把消息传递给下一个对象。对于这个模式应用的最经典的例子,应该是windows系统下的消息传递机制。这个可以参照侯捷老师的windows程序设计。那里很详细的介绍了windows消息处理。
- 设计模式学习-行为模式-职责链模式
- 设计模式-行为-职责链
- 设计模式深入学习--Chain of Responsibility 职责链模式职责链模式(行为型模式)
- 【JavaScript设计模式】行为型设计模式--职责链模式
- 行为模式-职责链模式
- 行为模式-职责链模式
- 设计模式 - 行为型模式 - 职责链模式
- 设计模式---行为类型---职责链
- 【设计模式学习笔记十四】【行为模式】【职责链模式(Chain Of Responsibility)】
- 设计模式笔记(20)---职责链模式(行为型)
- 设计模式19:职责链模式【行为型】
- java设计模式(行为型)之职责链模式
- 设计模式:行为模式:职责链(chain of responsibility)
- 【设计模式】行为模式之Chain of Responsibility职责链
- 设计模式学习----职责链模式
- 设计模式入门学习 职责链模式
- 设计模式学习(十六):职责链模式
- 设计模式学习笔记--职责链模式
- Jack测试架构师
- linux下IPTABLES配置详解推荐精华帖
- 中国移动MM7 API用户手册
- 一个外贸soho的生意经:逆向生意,正向赚钱
- RFC 2866 RADIUS Accounting -中文翻译
- 设计模式学习-行为模式-职责链模式
- wince屏幕滑动锁
- 读《影响力》
- 祥解C++中string
- PDF大全(转化、合并、编辑、阅读、注册码、破解、序列号) (转)
- Eclipse--java.lang.OutOfMemoryError: PermGen space
- 有关Lucene的问题(5):Lucene中的TooManyClause异常
- PDF大全(转化、合并、编辑、阅读、注册码、破解、序列号) (转)
- 有关Lucene的问题(6):Lucene的事务性