# 确定时间后,调用(通知)学生、助理和系主任 @stu.update(self) @assistant.update(self) @dean.update(self) end end
classStudent defupdate(prof) puts "start studying for Prof. #{prof.name} exam on the #{prof.exam_date}" end end classAssistant defupdate(prof) puts "find a classroom for Prof. #{prof.name} exam on the #{prof.exam_date}" end end classDean defupdate(prof) puts "go over for Prof. #{prof.name} exam on the #{prof.exam_date}" end end
stu = Student.new ass = Assistant.new dean = Dean.new prof = Professor.new("Jeff", "Software", stu, ass, dean) prof.set_midterm("2020-03-22")
moduleObservable defadd_observer(observer, func=:update) @observer_peers = {} unlessdefined? @observer_peers # 指定的调用函数必须能响应 unless observer.respond_to? func raiseNoMethodError, "observer does not respond to `#{func}'" end @observer_peers[observer] = func end
# 从@observer_peers中删除observer defdelete_observer(observer) @observer_peers.delete observer ifdefined? @observer_peers end
# 删除@observer_peers中所有observer defdelete_observers @observer_peers.clear ifdefined? @observer_peers end
# 统计observer的个数 defcount_observers ifdefined? @observer_peers @observer_peers.size else 0 end end
# 设置changed状态,默认状态为true defchanged(state=true) @observer_state = state end
defchanged? ifdefined? @observer_stateand@observer_state true else false end end
# 通过遍历@observer_peers,通知所有的observer并调用它们的调用函数 # 要求changed状态为true,同时设置changed状态为false defnotify_observers(*arg) ifdefined? @observer_stateand@observer_state ifdefined? @observer_peers @observer_peers.each do |k, v| k.send v, *arg end end @observer_state = false end end end
moduleObservable # 区分名称:notify_observer()和notify_observers() defnotify_observer(observer, *arg) ifdefined? @observer_peers raise"#{observer} is not a observer"unless@observer_peers.include? observer observer.send @observer_peers[observer], *arg end end end