我正在尽我所能用 Ruby 编写最安全的单例。我是这门语言的新手,它的弹性如此之大,以至于我没有强烈的感觉我的单例类会成功地只创建一个实例。作为奖励,我希望该对象仅在真正使用时才实例化。
最佳答案
# 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 会做什么?
- 它将
new
方法设为私有(private),因此您不能使用它。 - 它添加了一个名为 instance 的类方法,该方法仅实例化该类的一个实例。
所以要使用 ruby 单例模块你需要两件事:
- 需要库
singleton
然后将其包含在所需的类中。 - 使用
instance
方法获取您需要的实例。
关于ruby - 在 Ruby 中编写单例模式的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1482605/