Skip to content

Instantly share code, notes, and snippets.

@khanhicetea
Created May 2, 2015 04:14
Show Gist options
  • Save khanhicetea/1230893362e502f802fb to your computer and use it in GitHub Desktop.
Save khanhicetea/1230893362e502f802fb to your computer and use it in GitHub Desktop.
Design Patterns

Intent

  • Ensure that only one instance of a class is created.
  • Provide a global point of access to the object.

Implementation

Singleton Diagram

class Singleton
{
	private static Singleton instance;
	private Singleton()
	{
		...
	}

	public static synchronized Singleton getInstance()
	{
		if (instance == null)
			instance = new Singleton();

		return instance;
	}
	...
	public void doSomething()
	{
		...	
	}
}

Applicability

  1. Logger Classes
  2. Configuration Classes
  3. Accesing resources in shared mode
  4. Factories implemented as Singletons

Hotspot

  • Multithreading - A special care should be taken when singleton has to be used in a multithreading application.
  • Serialization - When Singletons are implementing Serializable interface they have to implement readResolve method in order to avoid having 2 different objects.
  • Classloaders - If the Singleton class is loaded by 2 different class loaders we'll have 2 different classes, one for each class loader.
  • Global Access Point represented by the class name - The singleton instance is obtained using the class name. At the first view this is an easy way to access it, but it is not very flexible. If we need to replace the Sigleton class, all the references in the code should be changed accordinglly.

Source : Singleton Pattern

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment