Chain of Responsibility模式
文中的代码示例,很是复杂,有重复,方法不关注
如handler中的:
@Override
public void handleRequest(Request request) {
if (request instanceof PrintRequest) {
request.execute();
} else {
System.out.println("PrintHandler can't handle " + request.getClass().getSimpleName());
if (successor != null) {
successor.handleRequest(request);
}
}
}
这个方法明显做了两件事,而且每个具体的handler中都得这样写。
所以现在重构下,把重复的事向上提一
层,并把方法分离成两个方法
Handler改成现在这个样:
package cor2;
/**
*
* @Filename: Handler.java
* @Description:Handler 作用:请求的发送者和接受者之间解耦
* 对@see cor1.Handler 进行了重构
*/
public abstract class Handler {
//下一个处理者
protected Handler successor;
/**
* template方法
* @param request
*/
public final void handleRequest(Request request){
if(canHandle(request)){
handle(request);
}else{
if(successor!=null){
successor.handle(request);
}
}
}
/**
* 是否可以处理此request
* @param request
* @return
*/
protected abstract boolean canHandle(Request request);
/**
* 具体处理请求
* @param request
*/
protected abstract void handle(Request request);
public Handler getSuccessor() {
return successor;
}
public void setSuccessor(Handler successor) {
this.successor = successor;
}
}
具体的单个Handler
package cor2;
public class PrintHandler extends Handler {
@Override
public void handle(Request request) {
System.out.println("PrintHandler handle " + request.getClass().getSimpleName());
request.execute();
}
@Override
protected boolean canHandle(Request request) {
if (request instanceof PrintRequest) {
return true;
}
return false;
}
}
request,client不变。优雅多了。
分享到:
相关推荐
23种设计模式之二十一(行为模式)Chain of Responsibility模式
C#面向对象设计模式 Chain of Responsibility 职责链模式 视频讲座下载
C#面向对象设计模式 (行为型模式) Chain Of Responsibility 职责链模式 视频讲座下载
设计模式C++学习之责任链模式(Chain of Responsibility)
NULL 博文链接:https://gary0416.iteye.com/blog/913457
C#面向对象设计模式纵横谈(20):(行为型模式) Chain Of Responsibility 职责链模式
chain of responsibility 职责链模式(行为模式)来自于Microsoft官方网站视频教程,详细介绍了职责链模式的运用,且在本人提供的资源里可以下载到相关的PDF辅助文档帮助
责任链模式(Chain of Responsibility Pattern)是一种常见的行为模式。 使多个对象都有处理请求的机会,从而避免了请求的发送者和接收者之间的耦合关系。将这些对象串成一条链,并沿着这条链一直传递该请求,直到有...
C#面向对象设计模式纵横谈(14):Chain of Responsibility 职责链模式(行为型模式) (Level 300)
【Java设计模式】(3)责任链Chain of Responsibility源码
Chain Of Responsibility.rar
C#面向对象设计模式纵横谈(14):Chain of Responsibility 职责链模式(行为型模式)
主要介绍了Java设计模式之责任链模式(Chain of Responsibility模式)介绍,本文讲解了如何使用责任链模式,并给出了4种使用实例,需要的朋友可以参考下
NULL 博文链接:https://linkcqu.iteye.com/blog/355806
设计模式-责任链的演示项目,导入eclipse中可直接运行,编程语言:java 设计模式学习请参考博客 https://www.li-tian.net.cn/archives/2020-01-27-23-01-15
NULL 博文链接:https://stelin.iteye.com/blog/932101
chain-of-responsibility-demo 责任链模式demo
设计模式精解-GoF 23 种设计模式解析附 C++实现源码 目 录 引 言 0.1 设计模式解析(总序) 0.2 设计模式解析后记 ...3.9 Chain of Responsibility模式 3.10 Iterator模式 3.11 Interpreter模式 4 说明
Design Pattern: Chain of Responsibility 模式 53 Design Pattern: Command 模式 59 Design Pattern: Interpreter 模式 Design Pattern: Iterator 模式 Mediator 模式 Memento 模式 Observer 模式 State ...