Coupling Systems Loosely with Callbacks : Observer « Design Patterns « Ruby






Coupling Systems Loosely with Callbacks


class MyObject 
  def initialize
    setup_listeners
  end

  def produce_widget(color)
    notify(:new_widget, color)
  end
  
  def setup_listeners
    @EventDispatcher_listeners = {}
  end

  def subscribe(event, &callback)
    (@EventDispatcher_listeners[event] ||= []) << callback
  end

  def notify(event, *args)
    if @EventDispatcher_listeners[event]
      @EventDispatcher_listeners[event].each do |m|
        m.call(*args) if m.respond_to? :call
      end
    end
    return nil
  end  
end
class MyObjectObserver
  def initialize(factory)
    @counts = Hash.new(0)
    factory.subscribe(:new_widget) do |color|
      @counts[color] += 1
      puts "#{@counts[color]} #{color} widget(s) created."
    end
  end
end

f1 = MyObject.new
MyObjectObserver.new(f1)
f1.produce_widget("red")
f1.produce_widget("green")
f1.produce_widget("red")

 








Related examples in the same category

1.Staying Informed (Observer pattern)
2.Add another observer
3.Code Blocks as Observers