初始化ruby singleton

时间:2012-05-24 08:24:14

标签: ruby singleton initialization rubymotion

我正在尝试初始化ruby中的单例。这是一些代码:

class MyClass
  attr_accessor :var_i_want_to_init

  # singleton
  @@instance = MyClass.new
  def self.instance
    @@instance
  end

  def initialize # tried 1. initialize, 2. new, 3. self.initialize, 4. self.new
    puts "I'm being initialized!"
    @var_i_want_to_init = 2
  end
end

问题是从不调用initialize,因此单例永远不会初始化。我尝试命名init方法initialize,self.initialize,new和self.new。没有任何效果。 “我正在初始化”从未打印过,当我用

实例化时变量从未初始化
my_var = MyClass.instance

如何设置单例以便初始化?帮助赞赏,

Pachun

2 个答案:

答案 0 :(得分:18)

standard library for singletons

require 'singleton'

class MyClass
  include Singleton
end

要修复代码,您可以使用以下代码:

class MyClass
  attr_accessor :var_i_want_to_init

  def self.instance
    @@instance ||= new
  end

  def initialize # tried 1. initialize, 2. new, 3. self.initialize, 4. self.new
    puts "I'm being initialized!"
    @var_i_want_to_init = 2
  end
end

答案 1 :(得分:6)

Rubymotion(1.24 +)现在似乎支持using GCD for singleton creation

class MyClass
  def self.instance
    Dispatch.once { @instance ||= new }
    @instance
  end
end