Thursday, November 20, 2014

Singleton Pattern - Simple tutorial with an example in Java

This pattern belongs to the category of creational design patterns. The concept of this pattern is can be described as below.

"This pattern does not let creating more than one instance of a certain object."

It means you can use this pattern when you want to restrict other classes creating more than one instance of a certain class.
How can we do that.
Think that the name of your class which is needed to be singleton is MySingleton. You can make the class singleton as below.

public class MySingleton {
private static MySingleton mySingleton;

//Make the constructor private so that
//any body cant use this to create instances
private MySingleton() {
}

//Calling this method is the only way of creating an
//instance of this class. If there is no previously created
//instance this method creates an instance and returns
//that. Otherwise returns the previously created instance.
public static MySingleton getInstance() {
if(mySingleton == null) {
mySingleton = new MySingleton();
}
return mySingleton;
}
}

You can test this class as below.

public class Test {
public static void main(String[] args) {
MySingleton ms1 = MySingleton.getInstance();
MySingleton ms2 = MySingleton.getInstance();

System.out.println(ms1 == ms2);//returns true because two instance are the same
}
}

No comments:

Post a Comment