我在下面实现了这个例子,以便在Ruby上使用Observer Pattern。我尝试了this,但没有效果。
require "observer"
class AAnyClass
extend Observable
changed
notify_observers self
end
module AnObserver
extend self
def update constant
p "Constant #{constant} has been called."
end
def observe constant
constant.add_observer(self)
end
end
AnObserver.observe AAnyClass
# must return "Constant AAnyClass has been called."
AAnyClass
# must return "Constant AAnyClass has been called."
AAnyClass
更新
我将模块AnObserver
转换为类,如下所示:
class AnObserver
def update constant
$stdout.puts "Constant #{constant} has been called."
end
end
更改类AAnyClass
,将Observable
方法添加到构造函数中,并将AnObserver
实例作为参数传递给方法add_observer
,如下所示:
class AAnyClass
include Observable
def initialize
add_observer AnObserver.new
changed
notify_observers AAnyClass
end
end
最后,我添加了一些代码,使用eigenclass
构造函数的相同代码修改了AAnyClass
AAnyClass’s
。
class << AAnyClass
extend Observable
add_observer AnObserver.new
changed
notify_observers AAnyClass
end
AAnyClass
AAnyClass.new
AAnyClass.new
就是这样。
答案 0 :(得分:1)
我认为你正在使用模块和#34;扩展&#34;你应该在哪里使用课程&#34;包括&#34;。这样的事情可能是你正在寻找的东西:
require "observer"
class AAnyClass
include Observable
def run
changed
notify_observers(self)
end
end
class AnObserver
def initialize(ob)
ob.add_observer(self)
end
def update constant
p "Constant #{constant} has been called."
end
def observe constant
constant.add_observer(constant)
end
end
ob = AAnyClass.new
AnObserver.new ob
ob.run