标签:责任链模式
责任链模式的重点是在“链”上,由一条链去处理相似的请求在链中决定谁来处理这个请求,并返回相应的结果,其通用类图如图16-4所示。
最核心的东西★
<span style="font-family:Microsoft YaHei;">public abstract class Handler { public final static int FATHER=1; public final static int HUSBAND=2; public final static int SON=3; private int level=0; private Handler nextHandler; //这是重点 public Handler(int _level){ this.level=_level; } public final void HandlerMessage(IWomen women){ if(women.getType()==this.level){ this.response(women); }else{ if(this.nextHandler != null){ this.nextHandler.HandlerMessage(women); }else{ System.out.println("没有后续,就是不同意"); } } } public void setNext(Handler _nextHandler){ this.nextHandler=_nextHandler; } protected abstract void response(IWomen women); }</span>
<span style="font-family:Microsoft YaHei;font-size:12px;">public class Father extends Handler { public Father() { super(Handler.FATHER); } @Override protected void response(IWomen women) { System.out.println("女儿向父亲请示:"+women.getRequest()); System.out.println("父亲答应"); } }</span>
<span style="font-family:Microsoft YaHei;font-size:12px;">public class Husband extends Handler{ public Husband() { super(Handler.HUSBAND); } @Override protected void response(IWomen women) { System.out.println("妻子的请示:"+women.getRequest()); System.out.println("丈夫准许了"); } }</span>
public class Son extends Handler { public Son() { super(Handler.SON); } @Override protected void response(IWomen women) { System.out.println("母亲的请示是"+women.getRequest()); System.out.println("儿子准许了"); } }
<span style="font-family:Microsoft YaHei;font-size:12px;">public interface IWomen { public int getType(); public String getRequest(); }</span>
<span style="font-family:Microsoft YaHei;font-size:12px;">public class Women implements IWomen { /* 0:未出嫁 * 1:已出嫁 * 2:丧夫 */ private int type=0; private String request=""; public Women(int type,String request){ this.type=type; this.request=request; } public String getRequest() { return this.request; } public int getType() { return this.type; } }</span>
<span style="font-family:Microsoft YaHei;font-size:12px;">public class Client { public static void main(String[] args) { Random random=new Random(); ArrayList<IWomen> list=new ArrayList<IWomen>(); for(int i=0;i<5;i++){ list.add(new Women(random.nextInt(4),"我要出去逛街")); //产生随机的类型 } Handler father=new Father(); Handler husband=new Husband(); Handler son=new Son(); father.setNext(husband); //设置下一个 husband.setNext(son); //设置下一个 for(IWomen women:list){ father.HandlerMessage(women); //当然从最高开始 } } } /** * 重要是"链",由一条链去处理相似的请求在链中决定谁来处理这个请求 */</span>
悟
这个设计模式一个最大的特点就是setNext()方法,可以往后传递从而实现递归一样的循环,如果这个不行,那就给下一个,链式结构的遍历。
"链",类似于if-else,显然这个设计的更高级,更工整。如果要说扩展性的话,那么还行吧,毕竟一个系统不可能有很长的责任链吧。可以和其他模式联合使用,关键还是场景,需求的问题。
我是菜鸟,我在路上。
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:责任链模式
原文地址:http://blog.csdn.net/cjvs9k/article/details/46971241