玩出花的职责链模式

来源:互联网 发布:在线随机抽签软件 编辑:程序博客网 时间:2024/05/29 07:32

最近看设计模式看到职责链模式,想到刚工作的时候,老大搞了一个职责链模式,玩的还挺高端的,所以又把以前的代码翻出来。

用我自己写的代码来描述,书里的职责链模式是这样的:

先来几个命令,不同的职责类来根据不同的命令做一些操作

public interface Command {}
public class N1Command implements Command {}
public class N2Command implements Command {}
然后是职责链的节点

public interface Node<T extends Command> {    void setNextNode(Node<Command> nextNode);    void execute(T command);}
public class Node1 implements Node<Command> {    private Node<Command> nextNode;    public void setNextNode(Node<Command> nextNode){        this.nextNode = nextNode;    }    public void execute(Command command) {        if(command instanceof N1Command){            System.out.println("Node1");        } else if(null != nextNode){            nextNode.execute(command);        }    }}
public class Node2 implements Node<Command> {    private Node<Command> nextNode;    public void setNextNode(Node<Command> nextNode){        this.nextNode = nextNode;    }    public void execute(Command command) {        if(command instanceof N2Command){            System.out.println("Node2");        } else if(null != nextNode){            nextNode.execute(command);        }    }}
然后再客户端可以这么使用:
public static void main(String[] args) {        Node<Command> node1 = new Node1();        Node<Command> node2 = new Node2();        node1.setNextNode(node2);        node1.execute(new N2Command());}
这样不但可以把本来在一个方法中的N多if-else拆分开来,符合迪米特法则,同时如果有新的命令需要处理,只要新增一个Node就可以了,也符合开放封闭原则,但是还是有些差强人意,就是我每次新增一个Node,在客户端都需要new一个新的对象,然后做一个set操作形成新的链,还是有一部分需要修改,总之不够完美。

当初我的老大用了一种方法,为职责链模式加了一个List(当然我觉得不加也能实现相应的功能),然后写了一个handler来初始化整个链,每当有命令需要执行时,由这个handler来负责调用这个“链”,链里的节点通过反射机制装入链中。这样做以后,只需要在扩展的时候添加新的Node子类,客户端不再需要修改任何代码,也算是一种奇技淫巧。下面上代码:

这里需要一个Spring应用上下文工具

@Componentpublic class SpringContextUtil implements ApplicationContextAware {   private static ApplicationContext applicationContext; // Spring应用上下文环境   /*    *     * 实现了ApplicationContextAware 接口,必须实现该方法;    *     * 通过传递applicationContext参数初始化成员变量applicationContext    *     */   @Override   public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {      SpringContextUtil.applicationContext = applicationContext;   }   public static ApplicationContext getApplicationContext() {      return applicationContext;   }   public static<T> T getBean(Class<T> requiredType) {      return (T) applicationContext.getBean(requiredType);   }}
修改后的Node

public interface Node<T extends Command> {    boolean execute(T command, ExecuteChain chain);}
@Componentpublic class Node1 implements Node<Command> {    public boolean execute(Command command, ExecuteChain chain) {        if(command instanceof N1Command){            System.out.println("Node1");            return true;        } else  {            return chain.executeChain(command, chain);        }    }}
@Componentpublic class Node2 implements Node<Command> {    public boolean execute(Command command, ExecuteChain chain) {        if(command instanceof N2Command){            System.out.println("Node2");            return true;        } else {            return chain.executeChain(command, chain);        }    }}

现在需要一个执行链来放置这些节点

public class ExecuteChain {    private int index = 0;    private List<Node<Command>> nodes;    public ExecuteChain(List<Node<Command>> nodes){        this.nodes = nodes;    }    public boolean executeChain(Command command, ExecuteChain chain){        if(index >= nodes.size()){            return false;        }        return nodes.get(index++).execute(command, chain);    }}

一个handler来初始化这个链,通过反射拿到所有指定包下的Node

public interface ChainHandler {    boolean executeChain(Command command);}

public class ConcreteChainHandler implements ChainHandler {    private ExecuteChain chain;    {        List<Node<Command>> list = Lists.newArrayList();        Reflections reflections = new Reflections("com.aurora.chain");        Set<Class<? extends Node>> subTypes = reflections.getSubTypesOf(Node.class);        for (Class<? extends Node> klass : subTypes) {            Node<Command> node = SpringContextUtil.getBean(klass);            list.add(node);        }        chain = new ExecuteChain(list);    }    public boolean executeChain(Command command) {        return chain.executeChain(command, chain);    }}
这样客户端调用的时候只需要执行一下代码:

ConcreteChainHandler concreteChainHandler = new ConcreteChainHandler();concreteChainHandler.executeChain(new N2Command());

而当需要扩展Node的时候,并不需要修改代码,只需要新增Node类的子类就可以了,当然,需要在指定的包下,因为要通过反射来得到子类的实例。

以上只是一个demo,还有很多问题需要完善,但是一个花式职责链的框架已经有了。