标签:handles 变量 道德 log iss 成员 类图 until protect
责任链模式的重点是在“链”上。由一条链去处理相似的请求在链中决定谁来处理这个请求,并返回对应的结果,其通用类图如图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。显然这个设计的更高级,更工整。假设要说扩展性的话,那么还行吧。毕竟一个系统不可能有非常长的责任链吧。能够和其它模式联合使用,关键还是场景,需求的问题。
我是菜鸟,我在路上。
标签:handles 变量 道德 log iss 成员 类图 until protect
原文地址:http://www.cnblogs.com/gccbuaa/p/6786393.html