Created
February 25, 2018 15:02
-
-
Save suryart/0c67490fa44eeabbefa2a9ab13725cd1 to your computer and use it in GitHub Desktop.
observer-pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Appliance | |
attr_accessor :name, :state , :switch | |
def initialize(name, switch = nil) | |
@name = name | |
@state = switch.nil? ? :off : switch.state | |
@switch = switch | |
end | |
def update(changed_state) | |
self.state = changed_state | |
end | |
def on? | |
self.state == :on | |
end | |
def off? | |
self.state == :off | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Observer | |
attr_reader :observers | |
def initialize | |
@observers = [] | |
end | |
def add_observer(observer) | |
@observers << observer | |
end | |
def delete_observer(observer) | |
@observers.delete(observer) | |
end | |
def notify_observers(method = :update) | |
self.observers.map do |observer| | |
if observer.respond_to?(method) | |
observer.send(method, self.state) | |
else | |
raise NoMethodError, "undefinded method #{method.to_s}" | |
end | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
switch_box = SwitchBox.new(argf.gets.chomp) | |
switch1 = Switch.new(argf.gets.chomp, :off) | |
switch_box.switches << switch1 | |
appliance = Appliance.new(argf.gets.chomp) | |
appliance.switch = switch1 | |
switch1.add_observer(appliance) | |
puts "Switch named '#{switch1.name}' is currently #{switch1.state.to_s.upcase}" | |
puts "Appliance '#{appliance.name}' is currently #{appliance.state.to_s.upcase}" | |
puts '-'*10 | |
puts 'Changing switch state!!' | |
switch1.state = :on | |
puts 'Switch state has been changed!!' | |
puts '-'*10 | |
puts "Switch named '#{switch1.name}' is now #{switch1.state.to_s.upcase}" | |
puts "Appliance '#{appliance.name}' is now #{appliance.state.to_s.upcase}" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SwitchBox | |
attr_accessor :name, :switches | |
def initialize(name) | |
@name = name | |
@switches = [] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment