Singleton - Creational Design Pattern (II)
8 March 2008Do read part I of this post. This post is about the implementation of singleton pattern.
Implementation
To prevents the direct instantiation of the object by other classes the class’s default constructor is made private. As a result the object cannot be instantiated any other way. The class has a static reference to the only singleton instance and returns that reference from the static method. However in multi threaded applications the singleton pattern must be properly implemented.
The example below demonstrates the use of The Singleton Design Pattern. It uses methodology known as lazy instantiation to create the singleton. Note that the class implements a private constructor so clients cannot instantiate objects of it. The singleton instance is not created until the getInstance() method is called for the first time. This methodology makes sure that singleton instances are created only when needed.
Example
public class Singleton { // Note private constructor private Singleton() {} private static class SingletonInner { private final static Singleton instance = new Singleton(); } public static Singleton getInstance() { return SingletonInner.instance; } }
Related Posts:
- Singleton - Creational Design Pattern (I)
- The Strategy Design Pattern in Java(I)
- The Observer Design Pattern(I)
- Adapter design pattern
- Singleton Pattern
- The Facade Design Pattern (I)
- Design Patterns - Basics (I)
- The Strategy Design Pattern in Java(II)
- The Facade Design Pattern (II)
- Adapter design pattern (II)
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: Singleton - Creational Design Pattern (II)