Tuesday, July 8, 2008

Singleton means: instance, static, CloneNotSupported exceptoin and overriding constructor...

Whenever we(a majority of us, at least most people I have worked with) think of singleton, the idea of "static" comes into picture. But I always like to reiterate that it is not just static.

Developers in any language want a singleton because they are dealing with memory management and security of the code at run time.

Most of the time the "resources" we load when the application starts are going to be the same. For those things in application which strictly should be created once.

Singleton design for such objects can be adapted, and by that it just doesn't mean that we can do:

private NameOfSingletonClass(){
}

It must be more than that, most specifically: the code must account for the fact that any other class which gets a copy of the instance of the singleton class can always create a copy by using .clone(). Any java class can override the clone() method of type Object because all classes in java are descendants of the "grand daddy" class in java called "Object".

So to prevent that: we must also put a block of code as follows:

public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}

Now, to summarize on creating singleton class, please refer to the complete singleton class below, this is the best and the perfect in its grade to implement a singleton pattern(of course you will need it in your local package and named appropriately with other of your custom methods for your custom logic.

/**
* Object Comments go here...TODO
*/
package com.nirmal.singh.designpatterns.singleton
/**
* @author nsingh
*
*/

public class RealSingleton {

private static RealSingleton singleTonObjVar;

private RealSingleton() {
//no code implementation needed here
//this is just to override the default constructor
}

public static RealSingleton getSingletonObject() {
//checking for null to find out if it is the first time
//this singleton needs to be created
if (singleTonObjVar == null)
singleTonObjVar = new RealSingleton();
return singleTonObjVar;
}

//any java class can invoke a clone() method to clone this
//singleton if we do not include the method below
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}

Thanks for reading...happy coding!!