Saturday, December 1, 2012

Basics of Design Patterns!!!

A good design saves a lot of coding issues while providing you better code re-usability and maintainability - Mostly used phrase in Software Industry. While some follow it and some simply don't care.

Hey, I got stuck somewhere !!! I need a solution to do this !
Not only you but billions of the Developers out there face some problems. And why only talking about Software Developers ?
Anyone in this world has to face some kind of challenges in their own field of work. May it be a Software Developer, may it be a Civil Engineer, may it be an Electrical Engineer or may it be anyone.

So, what's the point here ?
The point here is very much simple, we face problem and seek solution. In Software Industry also, some solution approach is defined to have some control over the problem we face. Those are known as Design Patterns.

Well, good enough So, what are they ?
Design Pattern: Design Pattern is a general reusable, time-tested solution to a set of commonly occurring problems. This is just a guide to follow to save your application from creating the mess that has already done by many a few earlier.
Design patterns are extensions to OOP.

What if, I don't follow them ?
No problem, at all. You are not bound to follow them. You are a free bird while it comes to your application. But with your application growing, you can gradually feel the urge to incorporate Design Pattern in your application.

OK. I am a newbie in Java. Should I also follow them ?
Hey, no one except JVM is a 100% Guru in Java. No one, can wholly master any language or platform. But, you need the basic concept of OOP and some exposure to real world problems to relate and incorporate Design Pattern in your work. If you are a professional Developer, you might have get some knowledge already while working.

Where did this hell come from ?
Its not from Software Industry. The idea of design pattern came from an architecture industry. back in 1977 Christopher Alexander, a civil engineer wrote about his experience in solving design issues with some design constructs which proved to be successful over time and lead to desired desired effect. So, he thought of the benefit of society and documented them for other's use.
How good he was.
In Software Industry this first came to existence in 1987 when Kent Beck and Ward Cunningham began experimenting with the idea of applying patterns to programming and presented their results at the OOPSLA conference that year.
But design patterns gained popularity in 1995 with the Gang of Four (popularly known as, GoF) with the creation of  Design Patterns: Elements of Reusable Object-Oriented SoftwareAddison-WesleyISBN 0-201-63361-2.
Gang of Four members: Gamma, ErichRichard HelmRalph Johnson, and John Vlissides

What I am supposed to do with them ?
As per the definition, design pattern is a guide to some commonly known problems. If you follow the guide, you are supposed be avoiding many situation that causes nightmare and also can speed up your development process.

OK. are there any well known example you can provide ?
There are many. Java itself follows many design patterns on its own. While framework based on Java like Spring, Hibernate, GWT, JSF use many design patterns. I am listing a few here,
Java: Observer Pattern for Event Listeners
Java: Composite Pattern for File and XMLReader utilities
Java: Decorator pattern for I/O
Hibernate: Factory pattern in SessionFactory
JSF: JSF is based on the concept of MVC pattern

OK, you take a lot of name. What are they ?
They are actually design patterns used in different scenarios while working with Java. Good news is that, you also have followed design patterns in your code unknowingly like, Interface pattern, Abstract Parent Class pattern etc.

OK, I got it. So what next ?
Seems like, you got some interest in this !!!
Great...
I will now move on to different types of patterns in my next article.
Palash Kanti Kundu

Singleton

Why Singleton ?
Some objects are heavy to instantiate and meant to be instantiated only once throughout the application lifetime.
Some objects like database connection, window frame for GUI application, Network sockets etc.
That's what we need sometimes need to write programs keeping such situations in mind.

What is Singleton ?
Before the concepts of computer, Singleton meant a set with exactly one element in it. You can get the details here.
In Computer Science and IT Industry, Singleton is a creational  Design Pattern. This basically gives you specialized suggestions while writing a singleton implementation.

OK, How to do that ?
We need to create only one object of this class. So, we need to how we can create objects. There are basically four ways, we can create an object of a class.

  1. Using new keyword
    The most common way to create object.
     MyObject object = new MyObject();
  2. Using clone()
    MyObject anotherObject = new MyObject();
    MyObject object = anotherObject.clone();
  3. Using Class.forName()
    MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();
  4. Using object deserialization
    ObjectInputStream inStream = new ObjectInputStream(anInputStream );
    MyObject object = (MyObject) inStream.readObject();
So, we know we can create objects in these ways. Now we have to restrict all these possibilities.

Hey, if you restrict all of them, then how the one object will be created ?
Well, we will do it in the class itself. I think you are aware of static methods.

OK, carry on...

Apart from the object creation techniques, we also need to take care of multi-threading as well. Cause, it can also create two objects at the same time.

OK, not much of theory at this point, let's get our hand dirty.

 package main;  
 import java.io.FileInputStream;  
 import java.io.FileOutputStream;  
 import java.io.IOException;  
 import java.io.ObjectInputStream;  
 import java.io.ObjectOutputStream;  
 import java.io.Serializable;  
 /**  
  * Singleton utility  
  *   
  * @author palash.k  
  *   
  */  
 class Singleton implements Cloneable, Serializable {  
      /**  
       *   
       */  
      private static final long serialVersionUID = 1L;  
      /*  
       * Private variable to hold the instance of the Singleton object  
       */  
      private static Singleton instance;  
      /**  
       * Private constructor to block instantiation using new and Class.forName()  
       */  
      private Singleton() {  
           // Dummy constructor  
      }  
      /**  
       * Instantiates this class if object is not available and returns the  
       * instance  
       *   
       * @return the singleton instance  
       */  
      public static Singleton getInstance() {  
           if (instance == null) {  
                synchronized (Singleton.class) {  
                     // Double checked thread locking  
                     if (instance == null) {  
                          instance = new Singleton();  
                     }  
                }  
           }  
           return instance;  
      }  
      /*  
       * (non-Javadoc)  
       *   
       * @see java.lang.Object#clone()  
       */  
      protected Object clone() throws CloneNotSupportedException {  
           throw new CloneNotSupportedException("Singleton class cannot be cloned");  
      }  
      /**  
       * This also returns the instance of the single ton class. Which ensures  
       * singleton behavior through deserialization.  
       *   
       * @return the instance of Singleton  
       */  
      public final Object readObject() {  
           return getInstance();  
      }  
 }  
 /**  
  * Class to get Singleton instance  
  *   
  * @author palash.k  
  *   
  */  
 class TrySingletonThread implements Runnable {  
      /*  
       * (non-Javadoc)  
       *   
       * @see java.lang.Runnable#run()  
       */  
      @Override  
      public void run() {  
           System.out.println(Thread.currentThread().getName()  
                     + " got singleton with ID: "  
                     + Singleton.getInstance().hashCode());  
      }  
 }  
 /**  
  * Singleton test  
  *   
  * @author palash.k  
  *   
  */  
 public class Main {  
      public static void main(String args[]) throws IOException {  
           // We'll try all possibilities. We can not use new keyword here. Trying  
           // others.  
           // Try Class.forName()  
           int i = 0;  
           try {  
                @SuppressWarnings("unused")  
                Singleton singleton = (Singleton) Class.forName("main.Singleton")  
                          .newInstance();  
           } catch (Exception e) {  
                e.printStackTrace();  
           }  
           Singleton singleton = Singleton.getInstance();  
           FileOutputStream fileOut = new FileOutputStream("singleton.ser");  
           ObjectOutputStream out = new ObjectOutputStream(fileOut);  
           out.writeObject(singleton);  
           out.close();  
           fileOut.close();  
           // Try deserialization  
           try {  
                FileInputStream fileIn = new FileInputStream("singleton.ser");  
                ObjectInputStream in = new ObjectInputStream(fileIn);  
                singleton = (Singleton) in.readObject();  
                in.close();  
                fileIn.close();  
           } catch (IOException ioe) {  
                ioe.printStackTrace();  
                return;  
           } catch (ClassNotFoundException c) {  
                c.printStackTrace();  
                return;  
           } catch (Exception e) {  
                e.printStackTrace();  
           }  
           // Try clone  
           try {  
                @SuppressWarnings("unused")  
                Singleton singleton2 = (Singleton) singleton.clone();  
           } catch (Exception e) {  
                e.printStackTrace();  
           }  
           // Try multi-threading  
           while (i < 10) {  
                Thread t = new Thread(new TrySingletonThread());  
                t.setName("Thread - " + i);  
                t.start();  
                i++;  
           }  
      }  
 }  
Put any value in the while loop, you will get only one instance of class Singleton.

I recently got a nice solution to performance bottleneck using this pattern. Server was crashed due to unnecessary instantiation of objects in our code. We used this pattern and server recovered from the crashing issue.


Prev
Palash Kanti Kundu