2014-05-23 5 views
0

와 객체를 집재 통지 :내가하고 싶은 어떤 추상적 인 방법

  • 순서대로 집재 객체를 통지 : B -> C -> D
  • 이 모듈에 대한 알림 방법을 구분합니다.

은 그 때 나는 아래의 코드 작성 : 사실

module AbstractModule 
def notifiable? 
    raise "this should be overriden" 
end 

def observers 
    raise "this should be overriden" 
end 

def notify 
    puts "#{self.class.to_s} notification" 
end 

def notify_all 
    notify 
    observers.map{|o| o.notify_all} if observers && notifiable? 
end 
end 

class B 
    include AbstractModule 
    def observers 
     c_objects = 2.times.map{ C.new } 
    end 

    def notifiable? 
     true 
    end 
end 

class C 
    include AbstractModule 
    def observers 
     d_objects = 3.times.map{ D.new } 
    end 
    def notifiable? 
     true 
    end 
end 

class D 
    include AbstractModule 
    def observers 
     nil 
    end 
    def notifiable? 
     false 
    end 
end 

obj = B.new 
obj.notify_all 

을 내 원하는 결과이고 그 결과는 다음과 같습니다

B notification 
C notification 
D notification 
D notification 
D notification 
C notification 
D notification 
D notification 
D notification 

하지만 함께 만족 해요 :

  • B, C, D는 observersnotifiable 방법을 구현해야합니다.

어떻게이 코드를 리팩터링합니까?

답변

1

루비는 duck typing을 기반으로합니다. 추상적 인 방법을 만들어서는 안됩니다. 간단히 은 그곳에있는이라고 가정하고 그렇지 않은 경우 오류가 발생합니다. 특정 방법을 사용할 수 있는지 알아 보려면 respond_to?

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 
+0

감사합니다. 알겠습니다. – jwako