:::: MENU ::::

Singleton pattern


It is a pattern that allows a class to be instantiated only once. By using it every service of the application use this object using the same access point. In order to avoid more than one instances of the same class being instantiated, the constructor is created private.

Utility

Very useful when creating loggers: the object is created once and it is used as many times as we want.

Example

We create a MySingleton class with a private constructor and an extra method that returns a string (to use it after in the Main class).

MySingleton.java

package com.luisgomezcaballero.singleton_demo;

public class MySingleton {

	private static MySingleton myInstance = null;

	private MySingleton() {
	}

	public static MySingleton getMyInstance() {
		if (myInstance == null) {
			return new MySingleton();
		} else {
			return myInstance;
		}
	}

	public String getString() {
		return "Hello World!";
	}
}

Then we create a Main class. Here we have to have in mind that we create out object and later we don’t create it with new, but we delegate this decision in the method of the class singleton, that decides if create it (in case it doesn’t exist) or reuse the one that exists.

Main.java

package com.luisgomezcaballero.singleton_demo;

public class Main {

	public static void main(String[] args) {

		MySingleton mySingleton = MySingleton.getMyInstance();

		System.out.println(mySingleton.getString());
	}

}

Repository

The code of this project can be located at https://github.com/luisgomezcaballero/singleton-demo.


So, what do you think ?