Ruby 使用 extend 做装饰模式 ,有没有办法退回上一层

shewer · 2018年11月05日 · 最后由 victor 回复于 2018年11月08日 · 1337 次阅读

如题 当我把 module B 及 C extendi 后
有没有方法拆掉 module C 谢谢

module B
   def name
         "B"  + super
    end  
end

module C
    def name
        "C" + super
    end
end
class A
    def  name
          "A"
    end

end
if __FILE__ == $0
   a= A.new
  puts a.name  #=> "A"
  puts  a.singleton_class.ancestors  # => [#<Class:#<A>0x00007fffd913a138>>, B, A, Object, PP::ObjectMixin, Kernel, BasicObject]

 a.extend(B)
 puts  a.name           # =>  "BA"
 puts  a.singleton_class.ancestors  # => [#<Class:#<A>0x00007fffd913a138>>, B, A, Object, PP::ObjectMixin, Kernel, BasicObject]

 a.extend(C)  
 puts  a.name         # => "CBA" 
 puts  a.singleton_class.ancestors  # => [#<Class:#<A>0x00007fffd913a138>> ,C, B, A, Object, PP::ObjectMixin, Kernel, BasicObject]

end

不能。除非你用 evil_ruby 的办法

再 extend B 就好了(待考证)

没有用,已经 extend 的 module 直接跳过 顺序不变 ( 和 module include 一样,已经载入的 module 不会再载入且顺序不变) 仍然是 C -> B -> A

需要 登录 后方可回复, 如果你还没有账号请 注册新账号