Implementing a Singleton Pattern

Singleton Patterns are a nice way to have an object that can only have one instance (e.g. a cache, connection pooling etc.).

The idea is that, instead of calling the classes constructor, you call a static method that returns a reference to the only instance:

Example Code:

public class mySingleton {

//The actual instance of the class, private static
private static my Singleton instance=null;

//PRIVATE constructor
private mySingleton() {
super();
      //whatever...
}

//this method is called instead of the constructor when you need an instance

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

}

It's a pitty that you can't return the instance via a reintroduced second constructor, and can't implement an interface with getInstance(), but it's still nicer than having to make sure that only one instance exists manually...

 

Share this article!

Follow us!

Find more helpful articles: