问题描述
我有一个Singleton类 ExchangeRegistry
,该类保留所有Exchange对象.
I have the a Singleton class ExchangeRegistry
which keeps all the Exchange objects.
无需致电: ExchangeRegistry.instance.exchanges
我希望能够使用: ExchangeRegistry.exchanges
这可行,但是我对重复感到不满意:
This works, but I'm not happy with the repetition:
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
我对类方法中的重复不满意.
I'm not happy with the duplication in the class methods.
我已经尝试过使用 Forwardable
和 SimpleDelegator
,但是似乎无法解决这个问题.(其中的大多数示例不是针对类方法,而是针对实例方法)
I've tried using Forwardable
and SimpleDelegator
but can't seem to get this to DRY out. (Most examples out there are not for class methods but for instance methods)
推荐答案
可转发模块将执行此操作.由于您要转发类方法,因此必须打开eigenclass并在此处定义转发:
The forwardable module will do this. Since you are forwarding class methods, you have to open up the eigenclass and define the forwarding there:
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:调用Singleton实例方法的DRY类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!