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

阅读更多

 

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);
 

你可能感兴趣的:(设计模式)