public abstract class Handler {
protected Handler successor;
public abstract void handlerRequest(String condition);
protected Handler getSuccessor() {
return successor;
}
public void setSuccessor(Handler successor) {
this.successor = successor;
}
}
public class ConcreteHandler1 extends Handler{
@Override
public void handlerRequest(String condition) {
// TODO Auto-generated method stub
// 如果是自己的责任,就自己处理,负责传给下家处理
if(condition.equals("ConcreteHandler1")){
System.out.println( "ConcreteHandler1 handled ");
return ;
}else{
System.out.println( "ConcreteHandler1 passed ");
getSuccessor().handlerRequest(condition);
}
}
public class ConcreteHandler2 extends Handler{
@Override
public void handlerRequest(String condition) {
// TODO Auto-generated method stub
// 如果是自己的责任,就自己处理,负责传给下家处理
if(condition.equals("ConcreteHandler2")){
System.out.println( "ConcreteHandler2 handled ");
return ;
}else{
System.out.println( "ConcreteHandler2 passed ");
getSuccessor().handlerRequest(condition);
}
}
}
public class ConcreteHandlerN extends Handler{
@Override
public void handlerRequest(String condition) {
// TODO Auto-generated method stub
System.out.println( "ConcreteHandlerN handled");
}
}
//测试
Handler handler1 = new ConcreteHandler1();
Handler handler2 = new ConcreteHandler2();
Handler handlern = new ConcreteHandlerN();
//链起来
handler1.setSuccessor(handler2);
handler2.setSuccessor(handlern);
//假设这个请求是ConcreteHandler2的责任
handler1.handlerRequest("ConcreteHandler2");
public static void main(String[] args) {
// TODO Auto-generated method stub
Handler handler1 = new ConcreteHandler1();
Handler handler2 = new ConcreteHandler2();
Handler handlern = new ConcreteHandlerN();
//链起来
handler1.setSuccessor(handler2);
handler2.setSuccessor(handlern);
//假设这个请求是ConcreteHandler2的责任
handler1.handlerRequest("ConcreteHandler2");
}
文章来源地址https://www.toymoban.com/news/detail-744469.html
文章来源:https://www.toymoban.com/news/detail-744469.html
到了这里,关于责任链模式(Chain of Responsibility)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!