更新时间: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?
new
方法设为私有,因此您可以new
method private and so you can’t use it.因此要使用ruby单例模块,您需要做两件事:
So to use ruby singleton module you need two things:
singleton
,然后将其包含在所需的类中。 instance
方法获取所需的实例。singleton
then include it inside the desired class.instance
method to get the instance you need.