Ruby 使用抽象方法通知聚束对象
我想:Ruby 使用抽象方法通知聚束对象,ruby,module,Ruby,Module,我想: 按顺序通知聚束对象: B->C->D 将通知方法与模块分开 然后我写了下面的代码: 模块抽象模块 def应报告? 提出“这应该被覆盖” 结束 def观察员 提出“这应该被覆盖” 结束 def通知 将“#{self.class.to#s}通知” 结束 def通知所有人 通知 观察员。映射{o | o.notify_all}如果观察员和应通知? 结束 结束 B类 包含抽象模块 def观察员 c_objects=2.times.map{c.new} 结束 def应报告? 真的 结束 结束
- 按顺序通知聚束对象: B->C->D
- 将通知方法与模块分开
模块抽象模块
def应报告?
提出“这应该被覆盖”
结束
def观察员
提出“这应该被覆盖”
结束
def通知
将“#{self.class.to#s}通知”
结束
def通知所有人
通知
观察员。映射{o | o.notify_all}如果观察员和应通知?
结束
结束
B类
包含抽象模块
def观察员
c_objects=2.times.map{c.new}
结束
def应报告?
真的
结束
结束
C类
包含抽象模块
def观察员
d_objects=3.times.map{d.new}
结束
def应报告?
真的
结束
结束
D类
包含抽象模块
def观察员
无
结束
def应报告?
假的
结束
结束
obj=B.new
通知所有人
实际上这是我想要的结果,结果是:
B notification
C notification
D notification
D notification
D notification
C notification
D notification
D notification
D notification
但我不满意:
- B、 C、D必须实施
和观察员
方法应报告
module Notifiable
def notify
puts "#{self.class.to_s} notification"
end
def notify_all
notify
observers.map{|o| o.notify_all} if respond_to?(:observers) && observers
end
end
class B
include Notifiable
def observers
c_objects = 2.times.map{ C.new }
end
end
class C
include Notifiable
def observers
d_objects = 3.times.map{ D.new }
end
end
class D
include Notifiable
end
obj = B.new
obj.notify_all