Singleton Pattern

This is the last of the creational patterns. In the earlier tutorials we have seen the factory method, the abstract factory pattern, the builder pattern and the prototype pattern. In this tutorial we will look at the Singleton pattern. The singleton pattern ensures that only once instance of a class is created and the client can request that instance from the class. Singleton pattern can be used in scenarios where only one instance of a class should be created. For example, in the prototype pattern we used a prototype manager. The prototype manager is a candidate for a singleton. A log manager can be a candidate for a singleton class.

Singleton classes are getting out of popularity and are regarded by some as mere globals. Whatever the case may be its good to know it and can come in handy during development. Look at this discussion on SO.

There are different ways to create singletons. Lets look at four of them:

Instance Created in accessor method

A private constructor is used to restrict creation of the object by external clients. The actual object is created once in the getInstance method. The problem is that if multiple clients access the getInstance method at the same time then there is a chance of multiple objects being created

Instance Created in synchronized accessor method

A private constructor is used to restrict creation of the object by external clients. The actual object is created once in the getInstance method. The getInstance method is synchronized ensuring that only once instance is ever created. The disadvantage is that synchronized makes it slower.

Instance Created in static block

A private constructor is used to restrict creation of the object by external clients. The instance is created when the class loads. There is therefore only one instance ever created, however the disadvantage is that the application startup is delayed.

Instance Created in inner static class.

A private constructor is used to restrict creation of the object by external clients. This is probably the most performant method of creating the instance. When a client calls the getInstance the inner static class is loaded and the instance of the singleton created. Even if multiple clients try to access the getInstance only one object will be created since the inner class is loaded exactly once.

This completes our tutorial on Singletons. To extend a singleton you would need to declare the constructor protected. This discussion on SO summarizes it.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.