Hatena::Groupruby

kdmsnrの日記

 | 

1000-01-05

Observer

12:41

class Employee
  def initialize(salary)
    @salary = salary
  end
  
  def update_salary=(new_salary)
    @salary = new_salary
      # ここで通知しないと!
      notify_observer
  end

  attr_accessor :observer
  def notify_observer
    # @observerが複数になってもOK
    @observer.update(self)  
  end
end

それObservableモジュールで(ry

13:02

require 'observer'

class Employee
  include Observable # オブザーバを扱うためのメソッドが用意されてる

  attr_accessor :salary
  def update_salary new_salary
    @salary = new_salary
    changed # フラグ変更ktkr
    notify_observers(self) # みんなに通知する
  end
end

# こいつらオブザーバ
class PayrollDepartment
  def update emp
    puts emp.salary
  end
end

class PayrollDepartment2
  def update emp
    puts emp.salary
  end
end

class PayrollDepartment3
  def update emp
    puts emp.salary
  end
end

emp = Employee.new
emp.add_observer(PayrollDepartment.new) # オブザーバ追加用のメソッドもある
emp.add_observer(PayrollDepartment2.new)
emp.add_observer(PayrollDepartment3.new)
emp.update_salary 100

 |