设计模式之略见一斑(命令模式Command)
??? 终于把构造模式的几种设计模式写完,接下来开始写的行为模式。说起Command我们就要想起菜单构造方法。
?
1.菜单命令:
我们常见的一种情况就是菜单命令,按钮监听。下面就举出一个常用的简单例子 :
public class Test { public static void main(String[] args) {JButton jb = new JButton();jb.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubdoSomething();}});}}?
设计JButton的时候我们没办法决定用户调用什么方法,什么时候调用, 所以我们提供一个外接口来响应用户的请求,并把具体响应内容对外给用户由用户决定响应内容。如上代码,当用户点击按钮时,调用的方法的actionPerformed(),当你创建该按钮方法时,可以使用对应于特定命令行为的actionPerformed()方法。给它绑定一个监听对象(ActionListener)。
?
2.使用command模式提供服务
?假设现在有一个新需求要求我们统计方法的执行时间。假设已经有一个接口Command.
public interface Command { public void execute();}?
还有一个计算该接口执行所需要的时间的方法:
/** * the time been used on Command * @param command * @return */public static long time(Command command){long t1 = System.currentTimeMillis();command.execute();long t2 = System.currentTimeMillis();return t2-t1;}?
我们可以使用如下方式来测试他所花的时间,并对该接口的方法做一实现
public static void main(String[] args) {Command command = new Command(){public void execute() {try {Thread.sleep(100);} catch (Exception e) {e.printStackTrace();}}};long actual = time(command);System.out.println(actual);}?3.Command模式与其他模式关系
??? 1).Command模式与解释器模式类似
????2).Comsmand模式也类似于Factory模式,在Factory中用户不知道何时创建对象,也不知道该实例化哪一个类。
??? 3).Command模式也经常与其它模式一起使用如上面提的actionListener,我们通常都是类先实现这个接口,然后再
addActionListener(this)。或者把当前的actionPerformed()用另一个类封装.