The Observer Pattern is useful when you need to inform other objects whenever one original change of object occurs. Such as SNS feeds feature, cache clear and so on...
Without this pattern the code will looks like below:
class Payroll def update( changed_employee ) puts("Cut a new check for #{changed_employee.name}!") puts("His salary is now #{changed_employee.salary}!") end end class Employee attr_reader :name, :title attr_reader :salary def initialize( name, title, salary, payroll) @name = name @title = title @salary = salary @payroll = payroll end def salary=(new_salary) @salary = new_salary @payroll.update(self) end end
payroll = Payroll.new fred = Employee.new('Fred', 'Crane Operator', 30000, payroll) fred.salary = 35000
class Employee attr_reader :name, :title attr_reader :salary def initialize( name, title, salary ) @name = name @title = title @salary = salary @observers = [] end def salary=(new_salary) @salary = new_salary notify_observers end def notify_observers @observers.each do |observer| observer.update(self) end end def add_observer(observer) @observers << observer end def delete_observer(observer) @observers.delete(observer) end end
fred = Employee.new('Fred', 'Crane Operator', 30000.0) payroll = Payroll.new fred.add_observer( payroll ) fred.salary=35000.0
class Subject 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 Employee < Subject attr_reader :name, :address attr_reader :salary def initialize( name, title, salary) super() @name = name @title = title @salary = salary end def salary=(new_salary) @salary = new_salary notify_observers end end
class Employee include Subject attr_reader :name, :address attr_reader :salary def initialize( name, title, salary) super() @name = name @title = title @salary = salary end def salary=(new_salary) @salary = new_salary notify_observers end end
observer.update(self, :salary_changed, old_salary, new_salary)