Java 如何实现@Singleton 注释?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18795041/
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
How can I implement @Singleton annotation?
提问by user1401472
Possibly a repeated question. But I need to implement something like
可能是一个重复的问题。但我需要实现类似的东西
@Singleton
public class Person {
}
That will ensure only single instance of Person object.
这将确保只有 Person 对象的单个实例。
One way is to make constructor private. But that makes the Singleton annotation redundant.
一种方法是将构造函数设为私有。但这使得 Singleton 注释变得多余。
I could not really understand if I can really restrict object creation to single object without making the constructor private.
我无法真正理解是否可以在不将构造函数设为私有的情况下将对象创建限制为单个对象。
Is that even possible?
这甚至可能吗?
采纳答案by gd1
No annotation can prevent a class from being instantiated. However, if you plan to implement something like a Dependency Injection framework, or just a simple object factory, then you can use reflection to read the annotation and prevent the class from being instantiated more than once, but I understand this is not the answer you were looking for.
没有注释可以阻止类被实例化。但是,如果您打算实现依赖注入框架之类的东西,或者只是一个简单的对象工厂,那么您可以使用反射来读取注释并防止类被多次实例化,但我明白这不是您的答案正在寻找。
You can actually think about dropping the singleton pattern and moving to some more modern solution like a proper DI framework, which can give you the same result - with more flexibility.
您实际上可以考虑放弃单例模式并转向一些更现代的解决方案,例如适当的 DI 框架,这可以为您提供相同的结果 - 具有更大的灵活性。
回答by Cruncher
public class ASingletonClass
{
private static ASingletonClass instance = null;
private ASingletonClass()
{
}
public static ASingletonClass getInstance()
{
if(instance==null)
{
instance = new ASingletonClass();
}
return instance;
}
}
This is the right way to implement singleton. The annotation cannot stop people from calling the public constructor.
这是实现单例的正确方法。注释不能阻止人们调用公共构造函数。
回答by Jayant Chauhan
You can also use lazy initialization of the class. Example code as below.
您还可以使用类的延迟初始化。示例代码如下。
class LazyInitialization implements PrintStatement {
private static LazyInitialization instance;
private LazyInitialization() {
}
static LazyInitialization getInstance() {
if (instance == null)
instance = new LazyInitialization();
return instance;
}
@Override
public void print() {
System.out.println("I am inside");
}
}