责任链模式也是行为型模式的一种,就是上每个对象都持有对下一个对象的引用,形成一条链,最上层的对象可以通过对下一个对象的引用,将请求传递给链中的任意一个对象。
为了说明责任链的用途,在这里先写一个没有使用责任链的例子
public interface GVnment { /** * 处理事情 */ public void HandleMess(); }
public class People { int things; public People(int things){ this.things = things; } public int getThings() { return things; } public void setThings(int things) { this.things = things; } }
public class TownGVment implements GVnment{ @Override public void HandleMess(People p) { System.out.println("人要做的事是:"+p.getThings()); System.out.println("我这个乡镇府可以办"); } }
public class CityGVment implements GVnment{ @Override public void HandleMess(People p) { System.out.println("人要做的事是:"+p.getThings()); System.out.println("我这个市镇府可以办"); } }
public class test { public static void main(String[] args) { People weakP = new People(0); if(weakP.getThings()==0){ GVnment tgVnment = new TownGVment(); tgVnment.HandleMess(weakP); }else if(weakP.getThings()==1){ GVnment cgVnment = new CityGVment(); cgVnment.HandleMess(weakP); } People weakPS = new People(1); if(weakPS.getThings()==0){ GVnment tgVnment = new TownGVment(); tgVnment.HandleMess(weakPS); }else if(weakPS.getThings()==1){ GVnment cgVnment = new CityGVment(); cgVnment.HandleMess(weakPS); } } }这里我们可以看得出来,我们调用者使用起来会比较麻烦,最可怜的就是这个people,不知道自己的事情哪里可以办,得一个一个试。所以就让责任链来解救他吧!!
责任链模式中我们只需要将people传递进去,至于谁去实现我们不用关心。
public abstract class GVnment { /** * 能做的事 */ private int wiCan; private GVnment nextGVnment; public GVnment(int canDo){ wiCan = canDo; } /** * 处理事情 */ public void HandleMess(People p){ if(p.getThings()==wiCan){ Handle(p); }else{ if(nextGVnment!=null){ nextGVnment.HandleMess(p); }else{ System.out.println("没人处理得了"); } } } public GVnment getNextGVnment() { return nextGVnment; } public void setNextGVnment(GVnment nextGVnment) { this.nextGVnment = nextGVnment; } protected abstract void Handle(People p); }
public class TownGVment extends GVnment{ public TownGVment() { super(0); } @Override protected void Handle(People p) { System.out.println("人要做的事是:"+p.getThings()); System.out.println("我这个乡镇府可以办"); } }
public class CityGVment extends GVnment{ public CityGVment() { super(1); // TODO Auto-generated constructor stub } @Override protected void Handle(People p) { System.out.println("人要做的事是:"+p.getThings()); System.out.println("我这个市镇府可以办"); } }
public class test { public static void main(String[] args) { People p = new People(0); People happyP = new People(1); GVnment tGv = new TownGVment(); GVnment cGv = new CityGVment(); tGv.setNextGVnment(cGv); tGv.HandleMess(p); tGv.HandleMess(happyP); } }