Java单子模式[英] Java Singleton Pattern

本文是小编为大家收集整理的关于Java单子模式的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

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

我使用 singleton设计模式

 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;
   }
 }

我的问题是如何在另一个 class中创建班级单例的对象?

我尝试过:

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

什么是正确的代码?

谢谢, Spencer

推荐答案

Singleton singleton = Singleton.getInstance();

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

由于您的Singleton实现远非安全 - 您的对象可以通过反射实例化,因此您可能需要基于

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 another class?

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

推荐答案

Singleton singleton = Singleton.getInstance();

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

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

其他推荐答案

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 getInstance method static, which you've done in your code above.)

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.

其他推荐答案

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 Singleton class? Or maybe you have imported a class called the same in some other package.