Command 命令模式
Create receiver, then create command and link it to the receiver if needed, then create sender and link it to the specific command. The command mode extract the command from the business, and set a sender and receiver. The sender send message to receiver by calling the command, but not call the receiver directly.
创建接收者,创建命令并且在有需要的时候把它连接到接收者,然后创建发送者并且把它连接到命令。命令模式从业务中抽出命令的部分,然后设置一个发送者和接收者。发送者通过调用命令向接受者发送信息,而不是直接调用接收者。
// Message
class TableInfo {
var tableNo: Int?
init(tableNo: Int) {
self.tableNo = tableNo
}
}
// Receiver
class Cooker {
func cookMeal(info: TableInfo) {
print("Cook meal for: \(info.tableNo!)")
}
func sayHello(info: TableInfo) {
print("Say hello to: \(info.tableNo!)")
}
func reheatFood(info: TableInfo) {
print("Reheat food for: \(info.tableNo!)")
}
}
// Command
protocol Command {
func execute(info: TableInfo)
}
// Concrete Command
class ServeCommand: Command {
var cooker: Cooker?
init(cooker: Cooker) {
self.cooker = cooker
}
func execute(info: TableInfo) {
cooker?.sayHello(info: info)
cooker?.cookMeal(info: info)
}
}
// Sender
class Waiter {
var command: Command
init(command: Command) {
self.command = command
}
func executeCommand(info: TableInfo) {
self.command.execute(info: info)
}
}
let cooker = Cooker() // receiver
let command = ServeCommand(cooker: cooker)// command 与 receiver 连接。
let waiter = Waiter(command: command) // sender 与 command 连接。
waiter.executeCommand(info: TableInfo(tableNo: 4)) // sender 发送消息,则由对应的 receiver 接收并且处理
// Print:
// Say hello to: 4
// Cook meal for: 4
命令模式的作用是,将消息发送者和接收者分离开,发送者只负责把消息发给 command 而不知道自己的消息会被谁处理,接收者只负责对特定的消息做处理而不知道消息是来自哪个发送者。如此一来就可以灵活地更换发送者而不引起接收者的不适,或者更换接收者而不引起发送者的不适。