【发布时间】:2017-09-18 00:37:35
【问题描述】:
我喜欢 Ruby,并且正在学习设计模式。这是命令模式的示例。领域模型如下:
- Command - 所有命令的通用接口
- OnCommand、OffCommand - 实现 Command 接口的特定命令,都使用 TV 对象作为接收器
- 按钮 - 使用 Command 对象获取结果
- RemoteContol - 客户端,初始化 Button 和 Command 对象 Button - 使用 Command 对象执行命令
- 电视 - 接收命令
这里是这个问题的一些代码:
class TV
def on
puts 'TV is on'
end
def off
puts 'TV is off'
end
end
class Command
class Error < StandardError; end
def execute
raise Error
end
end
class OnCommand < Command
attr_reader :tv
def initialize(tv)
@tv = tv
end
def execute
tv.on
end
end
class OffCommand < Command
attr_reader :tv
def initialize(tv)
@tv = tv
end
def execute
tv.off
end
end
class Button
attr_reader :command
def initialize(command)
@command = command
end
def execute_command
command.execute
end
end
class RemoteControl
attr_reader :tv
def initialize(tv)
@tv = tv
@buttons = {
on: Button.new(OnCommand.new(tv)),
off: Button.new(OffCommand.new(tv))
}
end
def use_button(name)
button(name).execute_command
end
private
def button(name)
@buttons.fetch name
end
end
这是用法示例:
tv = TV.new
remote_control = RemoteControl.new(tv)
remote_control.use_button(:on) # TV is on
remote_control.use_button(:off) # TV is off
我对命令模式的理解程度如何?这是一个很好的例子吗?
感谢任何想法
更新
我想将 TV 替换为 InfraredTransmitter 作为命令接收器将使示例更合适。因为只有电视本身才能执行“on”命令。 RemoteControl 可以物理访问其红外发射器,该发射器能够向电视发送不同的命令。
【问题讨论】:
标签: ruby design-patterns solid-principles command-pattern