命令模式示例混淆

时间:2017-04-26 10:52:01

标签: swift design-patterns

当我遇到" Command Pattern"时,我正在阅读Head-First Design Pattern一书。章节。我在Playground重新创建了这个例子:

protocol RemoteActions {
    func turnOn()
}

protocol Product {
    var description: String { get set }
}

struct Light: Product {
    var description: String
    // some other properties
}

struct Heater: Product {
    var description: String
    // some other properties
}

class LightOn: RemoteActions {

    var light: Light

    init(light: Light) {
        self.light = light
    }

    func turnOn() {
        print("\(light.description) on")
    }
}

class HeaterOn: RemoteActions {

    var heater: Heater

    init(heater: Heater) {
        self.heater = heater
    }

    func turnOn() {
        print("\(heater.description) on")
    }
}


class Remote {
    func doAction(action: RemoteActions) {
        action.turnOn()
    }
}

let r = Remote()
let l = Light(description: "light1")
let h = Heater(description: "heater1")
let lo = LightOn(light: l)
let ho = HeaterOn(heater: h)
r.doAction(action: lo)
r.doAction(action: ho)

我的意思是这种模式有什么好处?是的,我可以看到遥控器只会知道它的动作,但如果我想创建一个新的产品来打开和关闭怎么办?毫无疑问,我必须创建一个新的命令类"对?这使得本书中的这部分真的很愚蠢:

image from textbook

如果我们将行动纳入所述产品,那会不会更好?像这样:

protocol RemoteActions {
    func turnOn()
}

protocol Product: RemoteActions {
    var description: String { get set }
    func turnOn()
}

struct Light: Product {
    var description: String
    // some other properties
    func turnOn() {
        print("\(description) on")
    }
}

struct Heater: Product {
    var description: String
    // some other properties
    func turnOn() {
        print("\(description) on")
    }
}

class Remote {
    func doAction(product: Product) {
        product.turnOn()
    }
}

let r = Remote()
let l = Light(description: "light1")
let h = Heater(description: "heater1")

r.doAction(product: l)
r.doAction(product: h)

1 个答案:

答案 0 :(得分:0)

gof说:'Command模式允许工具包对象通过将请求本身转换为对象来请求未指定的应用程序对象。该对象可以像其他对象一样存储和传递。这种模式的关键是一个抽象的Command类,它声明了一个用于执行操作的接口。在最简单的形式中,该接口包括抽象的Execute操作。 Concrete Command子类通过将接收器存储为实例变量并通过实现Execute来调用请求来指定接收器 - 操作对。接收方具备执行请求所需的知识。'