如何实现@Singleton注释? [英] How can I implement @Singleton annotation?
问题描述
可能是一个重复的问题。但我需要实现类似
Possibly a repeated question. But I need to implement something like
@Singleton
public class Person {
}
这将确保只有Person对象的单个实例。
That will ensure only single instance of Person object.
一种方法是将构造函数设为私有。但这使Singleton注释变得多余。
One way is to make constructor private. But that makes the Singleton annotation redundant.
我真的无法理解我是否真的可以将对象创建限制为单个对象而不会使构造函数变为私有。
I could not really understand if I can really restrict object creation to single object without making the constructor private.
这甚至可能吗?
推荐答案
没有注释可以阻止实例化类。但是,如果您计划实现类似依赖注入框架的东西,或者只是一个简单的对象工厂,那么您可以使用反射来读取注释并防止类被多次实例化,但我明白这不是您的答案正在寻找。
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.
你实际上可以考虑放弃单例模式并转向一些更现代的解决方案,比如一个合适的DI框架,它可以给你相同的结果 - 更灵活。
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.
这篇关于如何实现@Singleton注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!