Design Pattern - Singleton

The Singleton Design Pattern

1.1. Definition

The singleton Pattern ensures a class has only one instance, and provides a global point of access to it.

1.2. Usage

Singletons are useful to define classes which should only be available once, e.g. a model which is use in several view of an application, a logger or a device driver.
An example is an application which reads the data from a file into another class A. This content should be available in the whole application. Therefore the class A is defined as a singleton.
Another example would be the following View A and View B would like to display the same data of class with hold the data (model class). Using a singleton for the model class ensures that same data is used.

1.3. Code Example

The possible implementation of Java depends on the version of Java you are using.
As of Java 6 you can singletons with a single-element enum type.

package mypackage;

public enum MyEnumSingleton {
 INSTANCE;
 
 // other useful methods here
}

   
Before Java 1.6 a class which should be a singleton can be defined like the following.

public class Singleton {
 private static Singleton uniqInstance;

 private Singleton() {
 }

 public static synchronized Singleton getInstance() {
  if (uniqInstance == null) {
   uniqInstance = new Singleton();
  }
  return uniqInstance;
 }
 // other useful methods here
}

   

Tip

A single-type enum type is the best way to implement a singleton. Source: Effective Java from Joshua Bloch.

1.4. Evaluation

A static class with static method would result in the same functionality as a singleton. As singletons are define using an object orientated approach it is in general adviced to work with singletons.
Singleton violate the "One Class, one responsibility" principle as they are used to manage its one instance and the functionality of the class.
A singleton cannot be subclassed as the constructor is declared private.
If you are using multiple classloaders then several instances of the singleton can get created.

评论

此博客中的热门博文

AVR Tutorial - Input / Output

AVR ADC Analog to Digital Converter

Introduction to REST