我有一个 Singleton 类 ExchangeRegistry
它保留所有 Exchange 对象。
不需要调用:
ExchangeRegistry.instance.exchanges
我希望能够使用:
ExchangeRegistry.exchanges
这可行,但我对重复不满意:
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"
关于Ruby:DRY 类方法调用 Singleton 实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34828891/