Posts

Showing posts with the label Design Pattern

Better ways to implement Singleton in Java

Singleton Design pattern restrict creation of only once instance of a Class. That means inside a single JVM only one instance of the Singleton Class will be created.  In java we have broadly two options to implement Singleton. 1) Early Creation of the Object Instance. 2) Lazy Creation of the Object Instance: Here the instance is created on first invocation. Following example demonstrate how to implement Singleton in Java. Method 1: Early Creation of Object Instance public class SingletonClass { private static final SingletonClass INSTANCE = new SingletonClass(); //Private Constructor private SingletonClass () { //Do nothing } public static SingletonClass getInstance () { return INSTANCE ; } } Here the instance is created ahead even before calling the Class. We need to provide a private constructor otherwise Java Compiler will add a default Constructor. Method 2: Lazy Creation of Object Inst...

Design Pattern : Composite

Image
Type  Structural Design Pattern Summary In the composite pattern, a tree structure exists where identical operations can be performed on leaves(leaf nodes) and nodes (non-leaf nodes).  It allows a group of object to be treated as an instance of a single object. Advantage Clients use the Component Class Interface to interact with objects in the composite structure If call is made to a Leaf , the request is handled directly. If call is to a Composite , it forwards the request to its child components.   Details A node in a tree is a class that can have children. A node class is a 'composite' class. A leaf in a tree is a 'primitive' class that does not have children. The children of a composite can be leaves or other composites. The leaf class and the composite class share a common ' Component ' interface that defines the common operations that can be performed on leaves and composites. When an operation on a composite is performed, this oper...