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

标签 ruby design-patterns singleton

我正在尽我所能用 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 会做什么?

  1. 它将 new 方法设为私有(private),因此您不能使用它。
  2. 它添加了一个名为 instance 的类方法,该方法仅实例化该类的一个实例。

所以要使用 ruby​​ 单例模块你需要两件事:

  1. 需要库 singleton 然后将其包含在所需的类中。
  2. 使用instance方法获取您需要的实例。

关于ruby - 在 Ruby 中编写单例模式的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1482605/

相关文章:

c++ - 大数库的通用包装类

zend-framework - 关于存储库的域驱动设计问题

angularjs - 我的服务中的数据在我的 Angular Controller 中并不持久

ruby - 难倒点击与 nokogiri 和 Mechanize 的链接

ruby - Ruby 是编写平台独立桌面应用程序的好选择吗?

java - 从不同的请求返回不同的 JSON 对象

android - OpenGL ES 和线程结构

ruby - 验证框架的替代 Rails

ios - Riod-iOS错误:您没有写权限“Gem::FilePermissionError”

PHP Singleton 设计模式继承错误