Singleton Pattern
Author: Deron Eriksson
Description: This Java tutorial describes the singleton pattern, a popular creational design pattern.
Tutorial created using:
Windows Vista || JDK 1.6.0_11 || Eclipse JEE Ganymede SR1 (Eclipse 3.4.1)
A singleton is a class that is instantiated only once. This is typically accomplished by creating a static field in the class representing the class. A static method exists on the class to obtain the instance of the class and is typically named something such as getInstance(). The creation of the object referenced by the static field can be done either when the class is initialized or the first time that getInstance() is called. The singleton class typically has a private constructor to prevent the singleton class from being instantiated via a constructor. Rather, the instance of the singleton is obtained via the static getInstance() method. The SingletonExample class is an example of a typical singleton class. It contains a private static SingletonExample field. It has a private constructor so that the class can't be instantiated by outside classes. It has a public static getInstance() method that returns the one and only SingletonExample instance. If this instance doesn't already exist, the getInstance() method creates it. The SingletonExample class has a public sayHello() method that can be used to test the singleton. SingletonExample.javapackage com.cakes; public class SingletonExample { private static SingletonExample singletonExample = null; private SingletonExample() { } public static SingletonExample getInstance() { if (singletonExample == null) { singletonExample = new SingletonExample(); } return singletonExample; } public void sayHello() { System.out.println("Hello"); } } The Demo class obtains a SingletonExample singleton class via the call to the static SingletonExample.getInstance(). We call the sayHello() method on the singleton class. Executing the Demo class outputs "Hello" to standard output. Demo.javapackage com.cakes; public class Demo { public static void main(String[] args) { SingletonExample singletonExample = SingletonExample.getInstance(); singletonExample.sayHello(); } } Singleton classes are a useful way of concentrating access to particular resources into a single class instance. Related Tutorials:
|