1. The intent of the Chain of Responsibility is to avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. To apply this pattern, chain the receiving objects and pass the request along the chain until an object handles it, see pic:
If you use the CoR pattern, remember: (somewhat like " switch - case - default ")
- Only one object in the chain handles a request
- Some requests might not get handled
So, in Chain of Responsibility, an object model takes on the job of finding which object can satisfy a client's request, the class diagram:
Chain of Responsibility class diagram
Typically, request handlers are extensions of a base class that maintains a reference to the next handler in the chain, known as the successor
. For example, the code:
public abstract class HandlerBase {
...
public void handleRequest(SomeRequestObject sro) {
if(successor != null)
successor.handleRequest(sro);
}
}
A concrete extension of HandlerBase
might look like this:
public class SpamFilter extends HandlerBase {
public void handleRequest(SomeRequestObject mailMessage) {
if(isSpam(mailMessage)) { // If the message is spam
// take spam-related action. Do not forward message.
}
else { // Message is not spam.
super.handleRequest(mailMessage); // Pass message to next filter in the chain.
}
}
}
In my point of view, Chain of Responsibility pass or divides the resiponsibility to the objects in the chain.
It leads to simpler code in both the hierarchy and the client, which is the main advantage of this pattern.
分享到:
相关推荐
Java codes to study patterns
Go Design Patterns-Packt(2017),Go设计模式,英文书籍,pdf格式,欢迎下载
Design Patterns - Elements of Reusable Object-Oriented Software [English] Design Patterns 英文版 带书签 解压密码:123456
Design Patterns-Elements of Reusable Object-Oriented Software 英文无水印pdf pdf所有页面使用FoxitReader和PDF-XChangeViewer测试都可以打开 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源...
好东西大家分享~~~~~~~~~~~
GOF-设计模式-Design Patterns-英文原版-高清-有目录-有页码
Head-First-Design-Patterns的官方源码,帮助你更好地学习Head-First-Design-Patterns。
关于设计模式的英文教材,包含详细例子,值得一读
Design Patterns-Elements of Reusable Object-Oriented Software + 源代碼
Pro-Objective-C-Design-Patterns-for-iOS.pdf
Learn the structure of design patterns and how they are written Understand different pattern categories, including creational, structural, and behavioral Walk through more than 20 classical and modern...
https://github.com/kamranahmedse/design-patterns-for-humans 中文翻译,实例修改位JAVA代码
Real-Time Design Patterns - Robust Scalable Architecture for Real-Time
Learning-Python-Design-Patterns-Second-Edition.pdf
php设计模式-designpatterns-php
Laracasts - design -patterns -in- php 课程资源
C# 设计模式 design-patterns-c-sharp
Practical-Python-Design-Patterns-Pythonic-Solutions-to-Common-Problems.pdf
b站李建忠讲的C/C+设计模式的ppt, ... 设计模式(Design pattern)是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性。