确保类的单个实例的正确方法是什么? [英] What is the correct way of ensuring a single instance of a class?

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

问题描述

在java中,我将创建如下:

In java I would create something like this:

private static MyClass instance;

public static MyClass getInstance() {
  if(instance != null) {
    return instance;
  }
  instance = new MyClass();
  return instance;
}

在ruby中获得相同功能的适当方法是什么?

What is the appropriate way to obtain the same functionality in ruby?

更新:我读过关于'include Singleton',但是当我试图在irb上做Ruby 1.9时,我得到:

Update: I've read about 'include Singleton' but when I tried to do it in irb on Ruby 1.9 I got:

[vertis@raven:~/workspace/test]$ ruby -v
ruby 1.9.1p378 (2010-01-10 revision 26273) [i386-darwin9.4.0]
[vertis@raven:~/workspace/test]$ irb
irb(main):001:0> class TestTest
irb(main):002:1>   include Singleton
irb(main):003:1> end
NameError: uninitialized constant TestTest::Singleton
    from (irb):2:in `<class:TestTest>'
    from (irb):1
    from /usr/local/bin/irb:12:in `<main>'


推荐答案

现在已经有了如何在Ruby中做的答案,但我会先问你需要什么?

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

没有必要复制你的Java模式到Ruby。我从2005年开始做Ruby,从来没有需要一个单例类。

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.

我知道你在尝试smth:

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

但是你可以这样做:

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

因为只有一个类Klass你的问题是本地解决,并且较少输入:)

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

在Ruby中的类只是类的实例,所以他们可以拥有一个实例可以拥有的一切。

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

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

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