职责链模式(Chain Of Responsibility):使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。
类图:
代码:
publicabstractclass Handle {
protected Handle nextHandle;
publicvoid setHandle(Handle handle){
this.nextHandle=handle;
}
publicabstractvoid execute(String msg);
}
publicclass ConcreteHandle1 extends Handle {
@Override
publicvoid execute(String msg) {
if(msg.length()<10){
System.out.println("处理的信息为:"+msg);
}elseif(this.nextHandle!=null){
this.nextHandle.execute(msg);
}
}
}
publicclass ConcreteHandle2 extends Handle {
@Override
publicvoid execute(String msg) {
if(msg.length()>10){
System.out.println("信息"+msg+"过于复杂无法处理!!");
}elseif(this.nextHandle!=null){
}
}
}
publicstaticvoid main(String[] args) {
Handle h1=new ConcreteHandle1();
h1.setHandle(new ConcreteHandle2());
h1.execute("123asdf45");
h1.execute("abcdefghijklmnopqrstuvwxyz");
}
小结:
职责链模式本质上就是简化了if语句。他可以自由组合顺序,但是要注意判断的顺序,于处理到最后都没有匹配的处理(如本例的处理长度为10)。