Java Singleton模式 [英] Java Singleton Pattern

查看:93
本文介绍了Java Singleton模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我使用了 Singleton Design Pattern

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

//私有构造函数阻止从其他类实例化
private Singleton(){}

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

我的问题是如何创建类的对象单击另一个类?



我尝试过:

  Singleton singleton = new Singleton(); 
// error - constructor is private
Singleton singleton = Singleton.getInstance();
//错误 - 非静态方法无法从静态上下文中引用

什么是正确的代码?



谢谢,
Spencer

解决方案

<$ Singleton singleton = Singleton.getInstance(); p $ p>

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



由于您的 Singleton 实现远未安全 - 您的对象可以通过反射进行实例化,您可能需要基于 枚举


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

这篇关于Java Singleton模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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