What is the correct way of ensuring a single instance of a class? [duplicate]

試著忘記壹切 提交于 2019-12-05 23:40:25

there are already answers to how to do it in Ruby, but I'd ask first do you need to?

There is no need to copy your Java patterns to Ruby. I'm doing Ruby from 2005 and never did I need a singleton class.

Why do you need an instance to begin with? Why can't you just define class methods and call them on the class.

As I understand you are trying smth like:

instance = Klass.new
instance.foo
.. then somewhere else
instance = Klass.new # expecting this to return the same instance
instance.bar

But instead you can just do this:

Klass.foo
... in other place
Klass.bar

And since thre is only one class Klass your problem is natively solved and with less to type too :)

classes in Ruby are just instances of class Class, so they can have everything an instance can have.

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