加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift设计模式之命令模式

发布时间:2020-12-14 07:00:01 所属栏目:百科 来源:网络整理
导读:转自 Swift设计模式 原文 Design-Patterns-In-Swift // 命令模式 // 百度百科:一组行为抽象为对象,实现二者之间的松耦合 // 设计模式分类:行为型模式 /** * 命令接口 */ protocol LightCommand { /** 执行命令 - returns: 结果 */ func execute() - Strin

转自

  • Swift设计模式

原文

  • Design-Patterns-In-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()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读