责任链模式(chain of reaponsiblity Pattern):是将链中的每一个节点看作是一个对象,每一个节点对请求的处理不同(或者处理不同的请求),并且内部维护着下一个节点对象;一个请求进来,会从责任链的首部开始向下传递,直到有节点处理请求或者是走完整个链路;
优点:
1、将请求与处理进行解耦;
2、链路中的节点只需要处理自己关心的请求,对于自己不关心的请求放给下一个节点进行处理;
3、请求不需要知道链路结构,只需要等待链路处理的结果就行了;
4、链路的结构比较多灵活,可以更改链路的结构,动态的新增删除责任节点,符合开闭原则;
缺点:
1、责任链太长,或者请求处理的时间太长,会影响整个链路的性能;
2、如果节点间存在循环引用,会出现死循环,会导致整个系统崩溃;
以下是责任链模式的简单示例:
public class Member {
public Member(String name, String password, String operation) {
this.name = name;
this.password = password;
this.operation = operation;
}
public String name;
public String password;
public String operation;
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
public class Test {
public static void main(String[] args) {
Handler.innerHandler handler = new Handler.innerHandler();
handler.setHandler(new LoginHandler()).setHandler(new AuthorizationHandler()).setHandler(new GetInHandler());
handler.doHandler(new Member("tony","123", "get message"));
}
}
public abstract class Handler {
public Handler handler;
abstract Handler next(Handler handler);
abstract void doHandler(Member member);
public static class innerHandler{
private Handler head;
private Handler tail;
public innerHandler setHandler(Handler handler){
if(head == null ){
head = tail = handler;
}
tail.next(handler);
tail = handler;
return this;
}
public void doHandler(Member member){
head.doHandler(member);
}
}
}
public class LoginHandler extends Handler{
@Override
Handler next(Handler handler) {
this.handler = handler;
return this;
}
@Override
void doHandler(Member member) {
System.out.println("login");
if(this.handler != null){
this.handler.doHandler(member);
}
}
}
public class GetInHandler extends Handler{
@Override
Handler next(Handler handler) {
this.handler = handler;
return this;
}
@Override
void doHandler(Member member) {
System.out.println("getmessage");
if(this.handler != null){
this.handler.doHandler(member);
}
}
}
public class AuthorizationHandler extends Handler{
@Override
Handler next(Handler handler) {
this.handler = handler;
return this;
}
@Override
void doHandler(Member member) {
System.out.println("authorization");
if(this.handler != null){
this.handler.doHandler(member);
}
}
}
以下为责任链中几个类的结构关系图:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)