职责链模式:推卸责任

职责链模式是一种行为设计模式,它允许你将请求沿着处理者链进行传递,直到其中一个处理者能够处理该请求为止。

示例代码

// 抽象处理者
public abstract class Handler {
protected Handler successor;
public void setSuccessor(Handler successor) {
this.successor = successor;
}
public abstract void handleRequest(Request request);
}
// 具体处理者1
public class ConcreteHandler1 extends Handler {
public void handleRequest(Request request) {
if (request.getType() == RequestType.TYPE1) {
System.out.println("ConcreteHandler1 handles the request.");
} else if (successor != null) {
successor.handleRequest(request);
}
}
}
// 具体处理者2
public class ConcreteHandler2 extends Handler {
public void handleRequest(Request request) {
if (request.getType() == RequestType.TYPE2) {
System.out.println("ConcreteHandler2 handles the request.");
} else if (successor != null) {
successor.handleRequest(request);
}
}
}
// 请求类
public class Request {
private final RequestType type;
public Request(RequestType type) {
this.type = type;
}
public RequestType getType() {
return type;
}
}
// 请求类型枚举
public enum RequestType {
TYPE1, TYPE2
}
public class Client {
public static void main(String[] args) {
// Setup the chain of handlers
Handler handler1 = new ConcreteHandler1();
Handler handler2 = new ConcreteHandler2();
Handler handler3 = new ConcreteHandler3();
handler1.setSuccessor(handler2);
handler2.setSuccessor(handler3);
// Send requests to the first handler
handler1.handleRequest(new Request("Type1"));
handler1.handleRequest(new Request("Type2"));
handler1.handleRequest(new Request("Type3"));
}
}

涉及到的角色

角色 作用
Handler 定义处理请求的接口和知道“下一个处理者”
ConcreteHandler 具体的处理者
Client 请求者
posted @   穆海如枫  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
点击右上角即可分享
微信分享提示