Skip to content

Instantly share code, notes, and snippets.

@suryart
Created February 25, 2018 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suryart/0c67490fa44eeabbefa2a9ab13725cd1 to your computer and use it in GitHub Desktop.
Save suryart/0c67490fa44eeabbefa2a9ab13725cd1 to your computer and use it in GitHub Desktop.
observer-pattern
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
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
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}"
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