Tuesday, July 22, 2014

Singleton Design Pattern

Singleton design pattern is a simple yet very powerful and widely used design pattern.
This is a type of Creational design pattern. The purpose of this pattern is to restrict the creation of instance of a particular class to one. Such a class is called a singleton class.

We should consider making a class singleton if the class needs to execute a set of expensive one time operations before it can perform any of its behavior operation and multiple calls to its behavior can use the same loaded resources over and over again.

In java, we implement singleton pattern by making the class's constructor private. This restricts the public(outside) access to create class instance. Then we provide a public static method to have access to the single class instance created inside the same method.

Let us take an example.


// BEGIN - Singleton Sample Code

package com.teawithjava.patterns.singleton;

public class KeepMeSingle {

        private static KeepMeSingle instance;
     
        private KeepMeSingle() {
                //Load expensive resources to be used by the class later
                System.out.println("Singleton instance of class KeepMeSingle created");
        }
     
        public static KeepMeSingle getSingleton() {
                if (null == instance) {
                        System.out.println("Singleton instance is not created yet. So a KeepMeSingle instance will be created");
                        instance = new KeepMeSingle();
                }
                System.out.println("Retirned the Singleton instance of class KeepMeSingle");
                return instance;
        }
     
        public void method1() {
                System.out.println("Hello There, This is the Singleton instance reporting :) !!!");
        }
     
        public void method2() {
                System.out.println("Hello There, This is the same Singleton instance reporting again :) !!!");
        }
     
        //Test Main Method
        public static void main(String[] args) {
                KeepMeSingle.getSingleton().
method1();
                KeepMeSingle.getSingleton().
method2();
        }
}
 

// END - Singleton Sample Code 


Code Explanation:

  1. Create a class KeepMeSingle and make its constructor private 
  2. Create private static reference variable of KeepMeSingle and assign it to null. This is because we want to have only one instance of KeepMeSingle and reference it using this static variable.
  3. Create public static method getSingleton() to provide handle/reference to the outside classes. Notice we are checking if the static instance is null. If so we create an instance and assign it. Finally we return the singleton instance.
  4. method1() and method2() and some methods of the KeepMeSingle class for testing.
  5. In main() method, the first call to static method getSingleton() of KeepMeSingle get its instance created(calls constructor) and then calls method1().
  6. In main() method, second call to static method getSingleton() of KeepMeSingle returns the same instance created(does not call constructor) and then calls method2().

Monday, August 13, 2012

Coupling Vs Cohesion

Today I am going to address very simple question/topic yet very often asked in Java interviews.

First of all, Coupling and Cohesion, both, are very different in their meaning even though they may sound similar. I shall try to explain using plain examples.

Coupling:

Coupling is a measure of how closely two things are bound together, known to each other and dependent on each other. In OOP and Java, two classes C1 and C2 are said to be tightly coupled if a third class C3 can not  use C1 without knowledge of C2.
Usually this happens when the class C1 holds a reference of C2 as it's member or static variable.



A good program or software should avoid tight coupling as much as possible.

Cohesion:

Cohesion is the measure of keeping logically related(and only related) things together in a group. In Java, a high cohesion is achieved by defining only logically or meaningfully related functions in a class.

Example 1:

A Calculator class should define functions such as add(), subtract(), multiply() etc. It should, however, never define a function to walk(), which clearly is an unrelated function for the  Calculator class.



Example 2:

Similarly, a DateUtility class should define functions such as formatDate(), parseDate(), isAfterDate(), isBeforeDate() etc. It should, however, never define a function to reverseString(), which clearly is an unrelated function for a DateUtility class.


A good program or software should possess high cohesion as much as possible,

So essentially, a good program or software should possess loose coupling and high cohesion among its components.