简体   繁体   中英

How can I implement @Singleton annotation?

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.

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.

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");
   }
}

It is arguably best to have a stateless singleton:

public class Singleton {
    private static final Singleton INSTANCE = new Singleton();
    
    private Singleton() {}
    
    public static Singleton getInstance() {
        return INSTANCE;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM