"コマンドパターン"の章を見たときに、ヘッドファーストデザインパターンの本を読んでいます。私はプレイグラウンドの例を作り直しました:コマンドパターンの例の混乱
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)
私はこのパターンのメリットは何ですか?はい、私はリモコンがその動作についてのみ知っていることがわかりますが、オンとオフを切り替える新しい製品を作成したいのですが?私は間違いなく新しい「コマンドクラス」の権利を創造しなければなりませんか?これは本当に愚かな本の中でこの部分を作る:私達は言った製品にアクションを適合場合
はそれがより良いと思いませんか?このように:
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)
このパターンのメリットは何ですか?上で述べたように、必要なときはいつでもサブクラスとして各アクションを作成しなければならないので、たくさんのクラスを作成する必要があります。または、このパターンに特定のユースケースがありますか? –
テキストを挿入して削除するエディタを作成していて、多くのレベルで取り消しややり直しができる必要があるとします。 –