设计模式之 Command 命令模式:Swift 实现

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 而不知道自己的消息会被谁处理,接收者只负责对特定的消息做处理而不知道消息是来自哪个发送者。如此一来就可以灵活地更换发送者而不引起接收者的不适,或者更换接收者而不引起发送者的不适。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值