Current implementation dont have base class for Observers. Observer methods moved to module. This is a basic solution without any checkings.
module ObserverMethods
def initialize
@observers = []
end
def add_observer(observer)
@observers << observer
end
def delete_observer(observer)
@observers.delete(observer)
end
def notify_observers
@observers.each do |observer|
observer.update(self)
end
end
end
class Entity
include ObserverMethods
attr_reader :name, :description
def name=(value)
@name = value
notify_observers
end
def description=(value)
@description = value
notify_observers
end
end
class TxtObserver
def update(entity)
puts "txt: #{entity.name}, #{entity.description}"
end
end
class TxtConsoleObserver
def update(entity)
puts ">> #{entity.name}, #{entity.description}"
end
end
entity = Entity.new
entity.add_observer(TxtConsoleObserver.new)
entity.add_observer(TxtObserver.new)
entity.name = "Name"
entity.description = "Description"
$ ruby observer.rb
>> Name,
txt: Name,
>> Name, Description
txt: Name, Description