Java Singleton Example

Singleton is a design pattern in software engineering that a Singleton class can only instantiate one object. In Java, this can be accomplished by making the constructor of the class private so the object cannot be instantiated outside the class. In order to create the object, the object need to be created within the class, and assign it to a private static field variable. To get the object instance, we will need a public static method to return this object instance. Here is a very simple example of Singleton class in Java.

public class MySingleton {

	private static MySingleton instance = new MySingleton();
	public int counter=0;
	// This private constructor is to prevent this object get instantiated more than once.
	private MySingleton(){}
	public static MySingleton getInstance()
		return instance;
	public void increment()
	public static void main(String args[])
		MySingleton s = MySingleton.getInstance();		
		System.out.println(s.counter); //3
		MySingleton s2 = MySingleton.getInstance();
		System.out.println(s2.counter); //3 also, because s2 is the same instance as s, just two different variable pointing to the same instance
		String txt;
		txt = (s.equals(s2)) ? "same":"not same";
		System.out.println(txt); //same

Search within Codexpedia

Custom Search

Search the entire web

Custom Search