CSC/ECE 517 Fall 2007/wiki1b 7 c9: Difference between revisions
Jump to navigation
Jump to search
No edit summary |
No edit summary |
||
Line 12: | Line 12: | ||
<pre> | <pre> | ||
class FireEmergencyButton | class FireEmergencyButton | ||
def initialize(onCommands, offCommands) | |||
@onCommands = onCommands | |||
@offCommands = offCommands | |||
end | |||
def press | def press | ||
@onCommands.each{|command| command.call} | @onCommands.each{|command| command.call} | ||
Line 46: | Line 46: | ||
feb.depress | feb.depress | ||
< | </pre> |
Revision as of 20:05, 1 October 2007
Question
Take a case of the Command pattern and implement it as succinctly as possible in Ruby and Java. Compare the two implementations in terms of clarity and succinctness. The example should be a "real-world" example. While it may be grossly oversimplified for the purpose of illustration, it should not be totally contrived (i.e., should not raise the question, Why would anyone ever want to do that?).
Java Implementation
Ruby Implementation
class FireEmergencyButton def initialize(onCommands, offCommands) @onCommands = onCommands @offCommands = offCommands end def press @onCommands.each{|command| command.call} end def depress @offCommands.each{|command| command.call} end end waterSprayOnCommand = proc{puts "Started spraying water!"} waterSprayOffCommand = proc {puts "Stopped spraying water..."} fireAlarmOnCommand = proc{puts "Fire alarm is on!"} fireAlarmOffCommand = proc {puts "Fire alarm is off..."} fireStationCallCommand = proc{puts "Fire department is called!"} onCommands = [] onCommands << fireAlarmOnCommand onCommands << waterSprayOnCommand onCommands << fireStationCallCommand offCommands = [] offCommands << fireAlarmOffCommand offCommands << waterSprayOffCommand feb =FireEmergencyButton.new(onCommands, offCommands) puts "Fire Emergency Button is pressed!" feb.press puts "" puts "Fire Emergency Button is depressed!" feb.depress