---
title: "设计模式快速参考－命令模式"
author: "gurudk"
date: "2008-12-06T07:10:30Z"
tags: ["设计模式"]
slug: "untitled"
draft: false
lastmod: "2008-12-06T07:10:30Z"
id: 288034
url: "https://gurudk.iteye.com/blog/288034"
---

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