Possibly a repeated question. But I need to implement something like
@Singleton
public class Person {
}
That will ensure only single instance of Person object.
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.
Is that even possible?
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments