How do I create a Class using the Singleton Design Pattern in Ruby?

大城市里の小女人 提交于 2019-12-22 03:24:39

问题


The singleton pattern is a design pattern that is used to restrict instantiation of a class to one object instance. Although I know how to code the singleton pattern in C++ and Java, I was wondering if anyone know how to implement it in Ruby?


回答1:


Actually, the above answer was not completely correct.

require 'singleton'

class Example
  include Singleton
end

You also need to include the require 'singleton' statement.




回答2:


Use the singleton module:

class Clazz
  include Singleton
end

See http://www.ruby-doc.org/stdlib/libdoc/singleton/rdoc/index.html for more info.




回答3:


You could use modules to the same effect I believe, although its not "the singleton pattern" you can have global state that way (which is what a singleton is ! Naughty global state !).



来源:https://stackoverflow.com/questions/4677/how-do-i-create-a-class-using-the-singleton-design-pattern-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!