Thursday, February 20, 2014

How to break the Singleton Design pattern using reflection.


Here is the Sample program to break the traditional Singeton Design pattern using reflection API.

package com.dpatterns;

import java.lang.reflect.Constructor;

public class SingleTon
{
              private static SingleTon SINGLE_TON = null;
             
              private SingleTon()
        { 
        }
             
              public static SingleTon getSingletonInstance() {
                           if(SINGLE_TON == null){
                                         SINGLE_TON = new SingleTon();
                           }
                           return SINGLE_TON;
              }
             
             
              public static void main( String[] args )
              {
                      for(int i = 0 ; i < 5 ; i++){
                                   System.out.println("Same Instance:"+SingleTon.getSingletonInstance());
                      }
                      
                      //Break the singleton .
                      System.out.println("Oops your singleton doesnt work any more...");
                      Class<?> class1 = SingleTon.class;
                      Constructor<?>[]  constructor = class1.getDeclaredConstructors();
                      Constructor<?> constr = constructor[0];
                      constr.setAccessible(true);
                      for(int i = 0 ; i < 5 ; i++)
                      {
                                   System.out.println("Different Instances: "+ new SingleTon());
                      }
              }

}

Just copy the above code and run, you will same instances in first Sysout, and you will see different instances created using new operator in Second Sysout.


THANK YOU..

UA-41474183-1