微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift设计模式之命令模式

转自

原文

// 命令模式
// 百度百科:一组行为抽象为对象,实现二者之间的松耦合
// 设计模式分类:行为型模式

/** * 命令接口 */
protocol LightCommand {
    /** 执行命令 - returns: 结果 */
    func execute() -> String
}

/// 打开命令
class OpenCommand : LightCommand {
    let light:String

    required init(light: String) {
        self.light = light
    }

    func execute() -> String {
        return "Opened \(light)"
    }
}

/// 关闭命令
class CloseCommand : LightCommand {
    let light:String

    required init(light: String) {
        self.light = light
    }

    func execute() -> String {
        return "Closed \(light)"
    }
}

/// 台灯类
class TableLamp {
    let openCommand: LightCommand
    let closeCommand: LightCommand

    init(light: String) {
        self.openCommand = OpenCommand(light:light)
        self.closeCommand = CloseCommand(light:light)
    }

    func close() -> String {
        return closeCommand.execute()
    }

    func open() -> String {
        return openCommand.execute()
    }
}

let lightName = "名叫[Hello World!]的台灯"
let myTableLamp = TableLamp(light:lightName)

myTableLamp.open()
myTableLamp.close()

原文地址:https://www.jb51.cc/swift/323810.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐