定义 :Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request .Chain the receiving objects and pass the request along the chain until an object handles it
使多个对象都有机会处理请求,从而避免了请求的发送者和接受者之间的耦合关系。 将这些对象连成一条链,并沿着这条链传递该请求,知道有对象处理它为止
例子
package ChainOfResponiability; public interface Ixiaoming { int getType(); String getRequest(); }
package ChainOfResponiability; public class XiaoMing implements Ixiaoming{ private int type; private String request; /* * type=1 表示爸爸在家 * type=2 表示爸爸不在妈妈在家 * @see ChainOfResponiability.Ixiaoming#getType() */ public XiaoMing(int type,String request){ this.type=type; this.request=request; //方便显示 switch(this.type){ case 1: this.request="爸爸在家"+request; break; case 2: this.request="爸爸不在妈妈在"+request; } } @Override public int getType() { return type; } public String getRequest(){ return request; } }
package ChainOfResponiability; public abstract class Handler { protected final static int LEVEL1=1; protected final static int LEVEL2=2; private int level=0; public Handler(int level){ this.level=level; } public final void handleRequest(Ixiaoming xiaoming){ if(xiaoming.getType()==this.level) this.response(xiaoming); else{ if(this.nextHandler!=null) this.nextHandler.handleRequest(xiaoming); else System.out.println("熊孩子没人guan啦"); } } private Handler nextHandler; public void setNextHandler(Handler handler){ this.nextHandler=handler; } protected abstract void response(Ixiaoming xiaoming); }
package ChainOfResponiability; public class Father extends Handler{ public Father() { super(LEVEL2); } @Override protected void response(Ixiaoming xiaoming) { System.out.println("爸爸在家不许去"); } }
package ChainOfResponiability; public class Mother extends Handler{ public Mother() { super(LEVEL1); } @Override protected void response(Ixiaoming xiaoming) { System.out.println("爸爸不再快去吧"); } }
package ChainOfResponiability; import java.util.ArrayList; public class Client { public static void main(String []args){ ArrayList<Ixiaoming> list=new ArrayList<Ixiaoming>(); list.add(new XiaoMing(1,"我要出去玩")); list.add(new XiaoMing(2,"我要出去玩")); list.add(new XiaoMing(3,"我要出去玩")); Handler father=new Father(); Handler mother=new Mother(); father.setNextHandler(mother); for(Ixiaoming i:list) father.handleRequest(i); } }
看下优点:可动态添加处理程序,在无处理情况下还会提供错误处理。 Client 可以动态组装处理顺序比较方便,处理权掌握在处理链手中。
缺点: 性能问题。 链过长会导致严重的性能问题。