Monday, June 20, 2016

Simple Technique: How to implement @Singleton annotation in a class

If the class has @Singleton annotation, then your purpose would not solved.

@Singleton
public class MyClass { 
// Code
}
 
Because no annotation can prevent a class having public contructor being instantiated.
 
Just use following technique to your class being instantiated at most once 
in an application.
 
public class MyClass {
    private static MyClass instance = null;

    private MyClass() {
    }
    
    public static MyClass getInstance()
    {
        if(instance == null)
        {
            instance = new MyClass();
        }
        return instance;
    }
} 
 
 
 

No comments:

Post a Comment