user3684678
user3684678

Reputation: 561

Creating a singleton class

The Singleton's purpose is to control object creation, limiting the number of objects to one only. Below is a class with two public methods.I want to convert it to Singleton class.Does putting a private constructor enough to convert class to singleton class?What are the other ways by which we can make a class as Singleton?

 public class Singleton {


    public void abc(){
    }

    public void def()
    {
    }
 }

Upvotes: 0

Views: 78

Answers (1)

Kerkhofsd
Kerkhofsd

Reputation: 299

Indeed, google before posting. Here is an implementation of a Singleton class.

public class MySingleton {
    private static MySingleton mInstance= null;

    private MySingleton (){}

    public static synchronized MySingleton getInstance(){
        if(null == mInstance){
            mInstance = new MySingleton();
        }
        return mInstance;
    }
}

And use it like this:

MySingleton.getInstance().whateverMethodYouWant();

Upvotes: 4

Related Questions