java设计模式之Command模式

来源:互联网 发布:淘宝打单难不难 编辑:程序博客网 时间:2024/05/16 17:34

Command模式是对操作的统一封装。

典型的Command 模式需要有一个接口.接口中有一个统一的方法,这就是"将命令/请求封装为对象":

  public interface Command {

  public abstract void execute ( );

  }

 

 

具体不同命令/请求代码是实现接口Command,下面有二个具体命令

 public class IntegerCommand implements Command {

  public void execute( ) {

  //do IntegerCommand 's command

  }

  }

 

   public class CharCommand implements Command {

  public void execute( ) {

  //do CharCommand 's command

  }

  }

 

通常可以直接调用这两个Command,但是使用Command 模式,我们要将他们封装到黑盒子List 里去:

  public class producer{

  public static List produceRequests() {

  List queue = new ArrayList();

  queue.add( new IntegerCommand () );

  queue.add( new CharCommand () );

  return queue;

  }

  }

  这两个命令进入List 中后,已经失去了其外表特征,调用Command 模式:

  public class TestCommand {

  public static void main(String[] args) {

  List queue = Producer.produceRequests();

  for (Iterator it = queue.iterator(); it.hasNext(); )

  //取出List 中东东,其他特征都不能确定,只能保证一

  个特征是100%正确,

  // 他们至少是接口Command 的"儿子".所以强制转换

  类型为接口Command

  ((Command)it.next()).execute();

  }

  }

 

调用者基本只和接口打交道,不合具体实现交互,这也体现了一个原则,面向接口编程;

原创粉丝点击