命令模式 发表于 2019-12-09 | 阅读数 命令模式(Command Pattern)命令模式是一种行为模式,将执行操作的信息封装到命令对象中。它包含以下3个类型: invoker:储存和执行命令 command:将行为封装成对象 receiver:command所作用的对象 使用举例1.创建Receiver1234// MARK: - Receiverpublic class Door { public var isOpen = false} 2.创建Command123456789101112131415161718192021public class DoorCommand { public let door: Door public init(_ door: Door) { self.door = door } public func execute() { }}public class OpenCommand: DoorCommand { public override func execute() { print("opening the door...") door.isOpen = true }}public class CloseCommand: DoorCommand { public override func execute() { print("closing the door...") door.isOpen = false }} 3.创建invoker1234567891011121314151617181920// MARK: - Invokerpublic class Doorman { public let commands: [DoorCommand] public let door: Door public init(door: Door) { let commandCount = arc4random_uniform(10) + 1 self.commands = (0 ..< commandCount).map { index in return index % 2 == 0 ? OpenCommand(door) : CloseCommand(door) } self.door = door } public func execute() { print("Doorman is...") commands.forEach { $0.execute() } }} 4.使用命令模式1234567891011121314151617// MARK: - Examplepublic let isOpen = trueprint("You predict the door will be " + "\(isOpen ? "open" : "closed").")print("")let door = Door()let doorman = Doorman(door: door)doorman.execute()print("")if door.isOpen == isOpen { print("You were right! :]")} else { print("You were wrong :[")}print("The door is \(door.isOpen ? "open" : "closed").") 其他例子 改变一个视图的明亮程度:http://jackliu17.github.io/2016/06/03/iOS%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E5%91%BD%E4%BB%A4/ 与普通写法的比较:https://yq.aliyun.com/articles/37261 撤销操作:https://juejin.im/post/5844c329ac502e006ba97570 屏幕变量和撤销:https://www.jianshu.com/p/c62e1bc04bf1