Wednesday, April 13, 2011

Java Design Patterns - Singleton

There are many examples out on the internet to explain Singleton and this is one more redundant one from my side :)

What's a Design pattern?
A design pattern is just a way of writing your code or designing your application. How a con-man goes about executing his tricks, defines his "modus-operandi" or just "pattern" in ordinary english. Similarly there are some standard "patterns" defined by experts for software development, which we can use for handling a particular scenario or requirement. Though we have heard about only a handful of design patterns, there are more than 250 design patterns identified, including a "noodle" pattern, which defines coding in the most unstructured or unmaintainable format.

A singleton pattern is one of the design patterns which along with "Factory" falls under a broad category of design pattern called Creational design patterns. The class is coded in such a way that there can be only one instance of this object in the JVM( or app/web server memory). Common areas of usage for singleton design would be loggers, DB connection managers, service locators(another design pattern) etc.

Steps to create a singleton
  1. Create a no-args constructor for the class and make it private. This would prevent the class being instantiated in other classes.
  2. Create a method(say getSingleton ) which would be the only point of access for other classes. This method would return an object of the classMake this static, so that it can be called from other classes without any object instantiation. Also make it public method.
  3. Define a single variable of the same class and make it static(to make it accessible from the static method,getSingleton)
  4. Within the "singleton creator" or "provider" method, invoke the class's constructor only if an object has not been created already.

You can refer the sample code below for your reference.

Please let me know if this small article of mine was of help to you. Feel free to post any java related questions that you have and I shall try to answer them to the best of my knowledge.