---
# System prepended metadata

title: 命令模式 Command
tags: [Behavioral Patterns]

---

---
tags: Behavioral Patterns
---

# 命令模式 Command

-[不錯的參考](https://notfalse.net/4/command-pattern)

---


當Ａ要請求Ｂ執行任務時，Ａ會呼叫Ｂ然後Ｂ在完成任務，在這種情況下Ａ需直接和Ｂ進行溝通，就像Ａ是老闆，他要交代員工Ｂ去做事情一樣，如下圖。我們稱做Ａ為Sender，Ｂ為Reciver。
![](https://i.imgur.com/7oF6YU6.png)
但如果Sender需要Reciver**做很多事**怎麼辦？就像是老闆非常忙碌，他沒辦法提醒每個人該做什麼事情，那該怎麼辦？這時**老闆(Sender)** 可以使用**備忘錄(Command)**。他將任務寫在備忘錄上，再經由**秘書(Invoker)** 把任務交給**員工(Receiver)** 完成。
![](https://i.imgur.com/DS2020p.png)

### 架構
![](https://i.imgur.com/LGUL6OX.png)


### 角色
**Command：** 用來宣告執行操作的interface / abstract class。
**ConcreteCommand：** Command的實體物件，通常會持有Receiver，並呼叫Receiver的功能來完成命令要執行的操作。
**Receiver(接收者)：** 幹活的角色， 命令傳遞到被執行。
**Invoker(請求者)：** 接收並要求執行命令。
**Client(裝配者)：** 建立Command Object，組裝Command Object和Receiver
*Clinet並非客戶端的Client*

### The differences between Strategy and Command pattern
**Strategy pattern**
is used to specify **how something should be done**, and plugs into a larger object or method to provide a specific algorithm.
(same purpose but different approach)

**Command pattern**
is used to make an object out of **what needs to be done** -- to take an operation and its arguments and wrap them up in an object to be logged.
(different purpose)

> [name=貴全]