Ruby:调用Singleton实例方法的DRY类方法
发布时间:2020-12-17 01:35:57 所属栏目:百科 来源:网络整理
导读:参见英文答案 Calling a method of a Ruby Singleton without the reference of ‘instance’????????????????????????????????????5个 我有一个Singleton类ExchangeRegistry,它保存所有Exchange对象. 而不是需要打电话: ???ExchangeRegistry.instance.exch
参见英文答案 >
Calling a method of a Ruby Singleton without the reference of ‘instance’????????????????????????????????????5个
我有一个Singleton类ExchangeRegistry,它保存所有Exchange对象. 而不是需要打电话: 我希望能够使用: 这有效,但我对重复不满意: require 'singleton' # Ensure an Exchange is only created once class ExchangeRegistry include Singleton # Class Methods ###### Here be duplication and dragons def self.exchanges instance.exchanges end def self.get(exchange) instance.get(exchange) end # Instance Methods attr_reader :exchanges def initialize @exchanges = {} # Stores every Exchange created end def get(exchange) @exchanges[Exchange.to_sym exchange] ||= Exchange.create(exchange) end end 我对类方法中的重复感到不满意. 我已经尝试过使用Forwardable和SimpleDelegator,但似乎无法让它干掉. (大多数示例都不是类方法,而是例如方法) 解决方法
可转发模块将执行此操作.由于您要转发类方法,您必须打开特征类并在那里定义转发:
require 'forwardable' require 'singleton' class Foo include Singleton class << self extend Forwardable def_delegators :instance,:foo,:bar end def foo 'foo' end def bar 'bar' end end p Foo.foo # => "foo" p Foo.bar # => "bar" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |