1. 程式人生 > >Ruby設計模式-觀察者模式學習筆記

Ruby設計模式-觀察者模式學習筆記

nco utf-8 upd attr ttr rim chan utf ade

observer.rb
#!/bin/env ruby # encoding: utf-8 require ‘observer‘

class
CriminalMovement include Observable attr_reader :criminal def initialize(criminal) @criminal = criminal end def action(msg) changed notify_observers(criminal, msg) end end class Criminal attr_reader :name
def initialize(name) @name = name end end class FbiMovement attr_reader :fbi def initialize(fbi) @fbi = fbi end def update(criminal, msg) p criminal.name + msg + : + fbi.name + 收到 end end class Fbi attr_reader :name def initialize(name) @name = name end end
# 臥底 class Dinting def self.run crmn1 = Criminal.new(黑狗) crmn2 = Criminal.new(黑虎) fbi1 = Fbi.new(飛鷹1號) fbi2 = Fbi.new(飛鷹2號) fbi1_observer = FbiMovement.new(fbi1) fbi2_observer = FbiMovement.new(fbi2) crinimal1_observer = CriminalMovement.new(crmn1) crinimal2_observer
= CriminalMovement.new(crmn2) fbi_observers = [fbi1_observer, fbi2_observer] crinimal_observers = [crinimal1_observer, crinimal2_observer] fbi_observers.each do |fbi_o| crinimal_observers.each do |cri_o| cri_o.add_observer(fbi_o) end end crinimal1_observer.action(今天淩晨2點,南河小巷搶劫) crinimal2_observer.action(明天淩晨2點,愛河毒品交易) end end Dinting.run

程序運行結果:

"黑狗今天淩晨2點,南河小巷搶劫: 飛鷹1號收到" "黑狗今天淩晨2點,南河小巷搶劫: 飛鷹2號收到" "黑虎明天淩晨2點,愛河毒品交易: 飛鷹1號收到" "黑虎明天淩晨2點,愛河毒品交易: 飛鷹2號收到"

Ruby設計模式-觀察者模式學習筆記