定义:责任链模式是一种对象的行为模式。在责任链模式里,很多对象由每一个对象对其下家的引用而连接起来形成一条链。请求在这个链上传递,直到链上的某一个对象决定处理此请求。发出这个请求的客户端并不知道链上的哪一个对象最终处理这个请求,这使得系统可以在不影响客户端的情况下动态地重新组织和分配责任。
实例:我们定义一个boy,一个女孩会根据这个男孩的条件做出相应的判断,比如她先看这个boy有没有车,有车的话会继续往下看其它条件,如果没有车就是屌丝,没戏了,然后再看你有没有房,最后看你是不是真心的。
具体实现过程:
public abstract class Handler { protected Handler handler; public Handler getHandler() { return this.handler; } public void setHandler(Handler handler) { this.handler = handler; } public abstract void handleRequest(Boy boy); }
定义一个抽象类,用来根据当前的条件做出request,回应,具体实现不同的对象会不一样。下面是三个分别判断car、house、responsibility的类。
public class CarHandler extends Handler { public CarHandler(Handler handler) { this.handler = handler; } @Override public void handleRequest(Boy boy) { // TODO Auto-generated method stub if (!boy.isHasCar()) { System.out.println("I have no car.");//没车就这么结束了,没戏了。 } else { System.out.println("I have a car."); if (this.getHandler() != null) { this.handler.handleRequest(boy); } } } } public class HouseHandler extends Handler { public HouseHandler(Handler handler) { this.handler = handler; } @Override public void handleRequest(Boy boy) { // TODO Auto-generated method stub if (!boy.isHasHouse()) { System.out.println("I have no house."); } else { System.out.println("I have a house."); if (this.getHandler() != null) { this.handler.handleRequest(boy); } } } } public class ResponHandler extends Handler { public ResponHandler(Handler handler) { this.handler = handler; } @Override public void handleRequest(Boy boy) { // TODO Auto-generated method stub if (boy.isHasHeart()) { System.out.println("I have a kind heart."); } else { System.out.println("I am bad."); if (this.getHandler() != null) { this.handler.handleRequest(boy); } } } }
public class Boy { private boolean hasHouse; private boolean hasCar; private boolean hasHeart; public Boy(boolean house, boolean car, boolean heart) { this.hasHouse = house; this.hasCar = car; this.hasHeart = heart; } public boolean isHasHouse() { return this.hasHouse; } public boolean isHasCar() { return this.hasCar; } public boolean isHasHeart() { return this.hasHeart; } public void setHasHouse(boolean house) { this.hasHouse = house; } public void setCar(boolean car) { this.hasCar = car; } public void setHeart(boolean heart) { this.hasHeart = heart; } }
上面是一个Boy的类。
测试如下:
public class test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Boy boy = new Boy(false, true, true); Handler handler = new CarHandler(new HouseHandler(new ResponHandler( null))); handler.handleRequest(boy); } }
输出:
I have a car.
I have no house.
虽然是个good boy,但是还没有看到这个条件就被pass掉了。