Java 单例模式 [英] Java Singleton Pattern

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

问题描述

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

Answered - error was method wasn't static

我使用了单例设计模式

 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?

我试过了:

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

正确的代码是什么?

谢谢,斯宾塞

推荐答案

Singleton singleton = Singleton.getInstance();

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

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

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

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 单例模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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