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?
What is singleton? Singleton Pattern in android. A single instance of a class providing a global point of access to itself during the entire application's lifetime. @Singleton annotation in Dagger. A single instance of a class which is unique to a specific component, its access is limited to the scope of the component.
Start by making getInstance() synchronized? Not necessarily. You can initialize the instance immediately upon class initialization (which is guaranteed to be thread-safe), or, if you stick with lazy initialization, you have to make the instance reference volatile (Java 1.5+) and perform double-checked locking.
Eager initialization: In eager initialization, the instance of Singleton Class is created at the time of class loading, this is the easiest method to create a Singleton class. By making the constructor as private you are not allowing other class to create a new instance of the class you want to create the Singleton.
The most popular approach is to implement a Singleton by creating a regular class and making sure it has: A private constructor. A static field containing its only instance. A static factory method for obtaining the instance.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With