ITeye博客

设计模式快速参考-命令模式

gurudk · 2008-12-06 07:10 · 模式 · 设计模式 · Markdown

interface ICommand{
   void execute(IReceiver receiver);
}

//发送传真命令
class SendFaxCommand implenments ICommand{
   void execute(IReceiver receiver){
      receiver.do(this);
   }
}

class AttackCommand implements ICommand{
   void execute(IReceiver receiver){
      receiver.do(this);
   }
}

class General{
   public ICommand createCommand(String commandType){
      if(“发传真” == commandType){
         return new SendFaxCommand();
      }else if (“打仗” == commandType){
         return new AttackCommand();
      }
   }
}

interface IReceiver{
   void do(ICommand command);
}

class Secretary implements IReceiver{
   //将具体命令信息传入,如传真文件内容等。
   public void do(ICommand command){
      //发送传真
   }
}

class Soldier implements IReceiver {
   //将具体命令传入,如作战地点,作战目标等等。
   public void do(ICommand command){
      //打仗
   }
}

 

Client:

 

General pengDeHuai = new General();
Secretary pengDeHuaiSecretary = new Secretary();
Soldier zhangSan = new Soldier(“张三”);

ICommand sendFaxCommand =  pendDeHuai.creatCommand(“发传真”);
sendFaxCommand.execute(pengDehuaiSecretary);

ICommand sendFaxCommand =  pendDeHuai.creatCommand(“打仗”);
sendFaxCommand.execute(zhangSan);

评论(2)

  1. #2 楼 · he_lux · 2009-02-16 12:22

    能否加点文字说明呢?

  2. #1 楼 · peigen · 2008-12-10 09:59

    这样解释直观,稍微有点片面,呵呵,支持~~

评论功能维护中,当前仅展示历史评论。