Automatically add a subclass to registry

本秂侑毒 提交于 2021-02-08 03:32:48

问题


For each subclass of the BaseStrategy being declared, I want to add them to the BaseStrategy.strategies array to be used later. What I can do is add class method BaseStrategy.register_strategy and call it in each subclass. But this would be error prone. Instead, I want BaseStrategy.register_strategy automatically invoked if a new subclass of BaseStrategy being declared. How can I do that?


回答1:


Use inherited hook:

class BaseStrategy
  class << self
    def inherited(klass)
      register_strategy(klass)
    end

    def register_strategy(strategy)
      puts "Adding strategy #{strategy}"
    end
  end
end

class Foo < BaseStrategy
end


来源:https://stackoverflow.com/questions/41527994/automatically-add-a-subclass-to-registry

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!