且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Ruby中编写单例模式的正确方法是什么?

更新时间:2022-12-24 19:13:38

# require singleton lib
require 'singleton'
class AppConfig
  # mixin the singleton module
  include Singleton
  # do the actual app configuration
  def load_config(file)
    # do your work here
    puts "Application configuration file was loaded from file: #{file}"
  end
end

conf1 = AppConfig.instance
conf1.load_config "/home/khelll/conf.yml"
#=>Application configuration file was loaded from file: /home/khelll/conf.yml
conf2 = AppConfig.instance
puts conf1 == conf2
#=>true
# notice the following 2 lines won’t work
AppConfig.new rescue(puts $!)
#=> new method is private
# dup won’t work
conf1.dup rescue(puts $!)
#=>private method `new’ called for AppConfig:Class
#=>can’t dup instance of singleton AppConfig

的实例因此,当包含单例时,ruby会做什么?

So what does ruby do when you include the singleton module inside your class?


  1. 这会将 new 方法设为私有,因此您可以

  2. 它添加了一个名为instance的类方法,该方法仅实例化该类的一个实例。

  1. It makes the new method private and so you can’t use it.
  2. It adds a class method called instance that instantiates only one instance of the class.

因此要使用ruby单例模块,您需要做两件事:

So to use ruby singleton module you need two things:


  1. 需要lib singleton ,然后将其包含在所需的类中。

  2. 使用 instance 方法获取所需的实例。
  3. li>
  1. Require the lib singleton then include it inside the desired class.
  2. Use the instance method to get the instance you need.