Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement @Singleton annotation?

Tags:

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?

like image 561
user1401472 Avatar asked Sep 13 '13 20:09

user1401472


People also ask

What does @singleton annotation mean?

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.

How do you implement singleton annotation in Java?

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.

What is the best way to implement Singleton design pattern?

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.

How are singletons implemented?

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.


1 Answers

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.

like image 72
gd1 Avatar answered Nov 15 '22 12:11

gd1