在Ruby中编写单例模式的正确方法是什么? [英] What is the correct way to write a singleton pattern in Ruby?

查看:105
本文介绍了在Ruby中编写单例模式的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用Ruby编写最安全的单例。我是该语言的新手,它是如此灵活,以至于我没有那种强烈的感觉,我的单例类只能成功创建一个实例。作为奖励,我希望仅在真正使用该对象的情况下才能实例化该对象。

I'm trying to write the most secure singleton in Ruby that I can. I'm new to the language, which is so elastic that I don't have a strong feeling that my singleton class will be successful at creating only one instance. As a bonus, I'd like the object to only become instantiated if really used.

推荐答案

# 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.

这篇关于在Ruby中编写单例模式的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆