说明:观察者模式中存在两个模型,分别是观察者(observer)和被观察者(subject),当被观察者的信息发生变动的时候,会将信息推送给观察者。观察者的核心:观察者模式不是观察者真正的去观察被观察者,而是被观察者在发生改变的时候主动去通知被观察者

代码演示

#observer模式的初始模型,本质上就是一个strategy模型
#在下面的模型中,被观察者就是employee, 当其工资变动时,会发出相应的变动信息,Taxman就是观察者
class Employee
  attr_reader :name, :salary

  def initialize name, salary, taxman
    @name = name
    @salary = salary
    @taxman = taxman
  end

  def salary=new_salary
    @salary = new_salary
    @taxman.update(self) 
  end
end

class Taxman
  def update obj
    puts "Taxman notice: #{obj.name} now has a salary of #{obj.salary}"
  end
end

jack = Employee.new('jack', 3000, Taxman.new)
jack.salary = 3000

上面的代码只是说了一种observer,更为通用的observer是提供多个observer,下面是多个observer的代码演示

class Employ
  attr_reader :name, :salary

  def initialize(name, salary)
    @name = name
    @salary = salary
    @observers = []
  end

  def add_observer(observer)
    @observers << observer
  end

  def delete_observer(observer)
    @observers.delete(observer)
  end

  def notify_observer
    @observers.each do |observer|
      observer.update(self)
    end
  end

  def salary=(salary)
    @salary = salary
    notify_observer
  end
end

class Taxroll
  def update(context)
    puts "taxroll notice: #{context.name} salary changeed now the salary is #{context.salary}"
  end
end

class Taxman
  def update(context)
    puts "taxman notice: #{context.name} salary changeed now the salary is #{context.salary}"
  end
end

employ = Employ.new("jayzen", 3000)
employ.add_observer(Taxroll.new) #注册成为observer
employ.add_observer(Taxman.new) #注册成为observer
employ.salary = 4000

对上面的代码进行抽象,把observer的功能抽象出来成为module

module Observer
  def initialize
    @observers = []
  end

  def add_observer(observer)
    @observers << observer
  end

  def delete_observer(observer)
    @observers.delete(observer)
  end

  def notify_observer
    @observers.each do |observer|
      observer.update(self)
    end
  end
end


class Employ
  include Observer

  attr_reader :name, :salary

  def initialize(name, salary)
    super()
    @name = name
    @salary = salary
  end

  def salary=(salary)
    @salary = salary
    notify_observer
  end
end

class Taxroll
  def update(context)
    puts "taxroll notice: #{context.name} salary changeed now the salary is #{context.salary}"
  end
end

class Taxman
  def update(context)
    puts "taxman notice: #{context.name} salary changeed now the salary is #{context.salary}"
  end
end

employ = Employ.new("jayzen", 3000)
employ.add_observer(Taxroll.new)
employ.add_observer(Taxman.new)
employ.salary = 4000

subject和observer应该应该具备下面的功能

#subject的功能
1.增加observer
2.移除observer
3.通知observer

#observer
1.需要实现接收通知时候的具体表现

[参考](http://www.cnblogs.com/nbkhic/archive/2011/11/07/2238826.html)

results matching ""

    No results matching ""