Java 单例模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2832297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:23:02  来源:igfitidea点击:

Java Singleton Pattern

javadesign-patternssingletoninitialization

提问by Spencer

Edit: Answered - error was method wasn't static

编辑:回答 - 错误是方法不是静态的

I'm used the Singleton Design Pattern

我使用了单例设计模式

 public class Singleton {
   private static final Singleton INSTANCE = new Singleton();

   // Private constructor prevents instantiation from other classes
   private Singleton() {}

   public static Singleton getInstance() {
      return INSTANCE;
   }
 }

My question is how do I create an object of class Singleton in anotherclass?

我的问题是如何在另一个类中创建类 Singleton 的对象?

I've tried:

我试过了:

Singleton singleton = new Singleton(); 
// error - constructor is private
Singleton singleton = Singleton.getInstance();
// error - non-static method cannot be referenced from a static context

What is the correct code?

正确的代码是什么?

Thanks, Spencer

谢谢,斯宾塞

采纳答案by Bozho

Singleton singleton = Singleton.getInstance();

is the correct way. Make sure your getInstance()method is indeed static.

是正确的方法。确保您的getInstance()方法确实是static.

Since your Singletonimplementation is far from being safe - your object can be instantiated via reflection, you may want to create a singleton based on enum

由于您的Singleton实现远非安全 - 您的对象可以通过反射实例化,您可能希望基于enum

回答by Grzegorz Oledzki

This one:

这个:

 Singleton singleton = Singleton.getInstance();

should work. This is how you call static methods in Java. And the getInstance()method is declared as static. Are you sure you are using the very same Singletonclass? Or maybe you have imported a class called the same in some other package.

应该管用。这就是在 Java 中调用静态方法的方式。并且该getInstance()方法被声明为static. 你确定你使用的是同一个Singleton类吗?或者,您可能在其他包中导入了一个名为 same 的类。

回答by Etaoin

Singleton singleton = Singleton.getInstance();should work -- that error doesn't make sense, given your code; are you sure you're reporting it correctly? (It would make sense if you had forgotten to make the getInstancemethod static, which you've done in your code above.)

Singleton singleton = Singleton.getInstance();应该有效——鉴于您的代码,该错误没有意义;你确定你报告正确吗?(如果您忘记将getInstance方法设为静态,这将是有意义的,您在上面的代码中已完成此操作。)

The code you've given us for the class is correct.

您提供给我们的课程代码是正确的。

Lastly, one conceptual note: First, you aren't "creating an object of class Singleton" -- that's the whole point of a Singleton. :) You're just getting a reference to the existing object.

最后,一个概念说明:首先,您不是“创建单例类的对象”——这就是单例的全部意义。:) 您只是获得了对现有对象的引用。

回答by vijay.shad

There is nothing wrong in using

使用没有任何问题

Singleton singleton = Singleton.getInstance();
// error - non-static method cannot be referenced from a static context

This is the way to get the singleton object form the class. There must me something else. Please post some more details

这是从类中获取单例对象的方法。我必须有别的东西。请发布更多详细信息

回答by Vaishak Suresh

  1. since the constructor is private, it does not make sense to create an object using the constructor.
  2. you should be using public static Singleton getInstance(), but the implementation is not very correct.

    if (instance == null) {
    instance = new Singleton();
    }
    return instance;

  1. 由于构造函数是私有的,因此使用构造函数创建对象是没有意义的。
  2. 您应该使用public static Singleton getInstance(),但实现不是很正确。

    if (instance == null) {
    instance = new Singleton();
    }
    return instance;

This is how you should be doing it. This ensure that it creates the instance if it does not exist, or simply returns the existing instance. Your code would also do the same thing, but this add to the readability.

这就是你应该做的。这确保它在实例不存在时创建它,或者简单地返回现有实例。您的代码也会做同样的事情,但这会增加可读性。

回答by Vaishak Suresh

Since we doesn't want to allow more than one copy to be accessed. So We need to manually instantiate an object, but we need to keep a reference to the singleton so that subsequent calls to the accessor method can return the singleton (rather than creating a new one). Thats why is

因为我们不想允许访问多个副本。所以我们需要手动实例化一个对象,但是我们需要保留对单例的引用,以便后续调用访问器方法可以返回单例(而不是创建一个新的)。这就是为什么

Singleton singleton = Singleton.getInstance();

Correct way to access any singletonObject.

访问任何单例对象的正确方法。

回答by Patrik

since getInstance() method is "static" and instance field too, yo can use Singleton.getInstance(); Without creating new exeple of class. Thihs is the poit of singletone

由于 getInstance() 方法是“静态的”并且实例字段也是如此,您可以使用 Singleton.getInstance(); 无需创建新的类示例。这就是单调的重点

回答by user

It is still possible to create more than one instance of the class, as follows:

仍然可以创建多个类的实例,如下所示:

Singleton.getInstance().clone()