命令模式算是我在过往项目中除了单例模式、模版模式等简单的模式以外用的最频繁的一个设计模式。
个人感觉命令模式的魅力就在于把一个个request封装成一个个的object,非常方便扩展。命令模式类似Javascript中的回调函数一样,可以进行callback处理。当然最大的缺点就是当request过多时,Command类也会膨胀的厉害。
最近编码时想用命令模式,看书复习了下,却总感觉书上讲的没有我以前设计的一个命名模式框架好用。经过翻箱倒柜终于找出了以前设计的命令模式,这里记录下,方便以后使用。
Command接口
不再使用抽象类,改用接口。同样只有一个
1 2 3 |
public interface Command<T> extends Serializable{ public T execute(Context context) throws Exception; } |
Context类
Context类可以处理很多事情,比如类似SpringContext,比如结合策略模式和状态模式等,可以根据具体的需求来实现不同的Context类。
1 2 |
public class Context { } |
IEngine
IEngine接口为执行引擎接口,IEngine为直接调用命令的接口,类比为传统命令模式中的导演类(director)、执行类(Invoker)。
1 2 3 |
public interface IEngine { public <T> T execute(Command<T> command) throws Exception; } |
实现
1 2 3 4 5 6 7 8 9 10 |
public class Engine implements IEngine { private Context context; public Engine(Context context) { this.context = context; } public <T> T execute(Command<T> command) throws Exception { return command.execute(context); } } |
具体的Command示例1
本命令用于将两个参数相加并返回结果。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class AddCommand implements Command<Integer> { private Integer a; private Integer b; public AddCommand(Integer a, Integer b) { super(); this.a = a; this.b = b; } @Override public Integer execute(Context context) throws Exception { return a + b; } } |
具体的Command示例2
本命令用于将两个参数append在一起。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class ToStringCommand implements Command<String> { private String name; private Integer age; public ToStringCommand(String name, Integer age) { super(); this.name = name; this.age = age; } @Override public String execute(Context context) throws Exception { return name + ":" + age; } } |
测试
1 2 3 4 5 6 7 8 9 10 11 |
public class Client { public static void main(String[] args) throws Exception { IEngine engine = new Engine(new Context()); Integer i = engine.execute(new AddCommand(1, 2)); System.out.println(i); String s = engine.execute(new ToStringCommand("yurnom", 26)); System.out.println(s); } } |
运行结果
1 2 |
3 yurnom:26 |
优点与缺点
优点就是至少满足了命令模式的核心思想(好吧我要求好低)。还有一个可以算作优点的地方就是抛弃了具体的执行者类,所有的命令执行由命令的