参见英文答案 Calling a method of a Ruby Singleton without the reference of ‘instance’5个 我有一个Singleton类ExchangeRegistry,它保存所有Exchange对象. 而不是需要打电话: ExchangeRegistry.instance.exchanges 我希
我有一个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"
