Ruby:DRY 类方法调用 Singleton 实例方法

标签 ruby delegates singleton

我有一个 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

我对类方法中的重复并不满意。

我尝试过使用ForwardableSimpleDelegator但似乎无法将其干燥。 (大多数示例不是针对类方法,而是针对实例方法)

最佳答案

可转发模块将执行此操作。由于您要转发类方法,因此必须打开特征类并在那里定义转发:

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/

相关文章:

java - 玩! - 动态结束作业

java - 带对象锁的单例模式

ruby-on-rails - 如何将 rails 2.3.10 更新到 3.x

ruby - 在 Windows 的命令行中安装 github-pages gem 时出错

ios - 委托(delegate)了解由应用程序发起的电话通话何时结束

c# - 如何识别匿名函数

java - 在java中转换ruby unpack等效项

php - Ruby Time.now.to_i PHP 等效项

java - Java 中的函数指针/委托(delegate)?

c++ - 实现程序配置设置的好方法是什么?