Monday, July 21, 2008

Breaking the Singleton Pattern



Reactions 

I like design patterns. They provide intuitive and reusable solutions to many software design problems. Singleton is the most basic of them. I use it everywhere from creating a Library class which initialize series of application wide objects to threaded queues used by various components within a system to lazy write the data.

In a nutshell Singleton guarantees only one instance of a class. Simple enough. See the following code.



package home;

public class AlwaysSingle
{
private String _name = null;
private static AlwaysSingle _single = null;

private AlwaysSingle( String name )
{
_name = name;
}

public static AlwaysSingle getSingle( String name )
{
if( _single == null )
{
_single = new AlwaysSingle( name );
}
return _single;
}

public String getName()
{
return _name;
}
}


Hmm, can somebody tell me how can I have code coloring in Blogger?
[After writing this article I searched for online code beautifiers. Most of the tools do not perform code coloring. They are mere formatters and others are standalone! I will write one in free time.]

So, this code has private constructor and have a static instance which can only be reached by calling single entry point. Nothing can be done to create more instances. Class is final, so one can't do inheriting tricks.

Reflection. Ring any bells? I still have to see writing security contexts as part of standard development practices. Look at the following code snippet. Pretty straightforward. Here goes Singleton.


import home.AlwaysSingle;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Driver
{
public static void main(String[] args)
throws IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException
{
AlwaysSingle single = AlwaysSingle.getSingle("me");

System.out.println(single.getName());

Class klass = Class.forName("home.AlwaysSingle");

Class[] paramTypes = {
String.class,
};

Constructor one = klass.getDeclaredConstructor(paramTypes);
one.setAccessible(true);

Object[] ags = {
"you",
};

AlwaysSingle notanymore = (AlwaysSingle) one.newInstance(ags);

System.out.println(notanymore.getName());
}
}


I can automatically retrieve the knowledge I have regarding this class. Sorry for not discussing this code. I am out of time and lazy for that :). I am assuming anyone who cared to read after reflection will be able to figure out things.

2 comments:

Sebastiaan Deckers said...

Hey buddy, congrats on the new blog!

Here is a code beautifier that works on Blogger:
http://blog.gpowered.net/2007/07/howto-post-code.html

Mohit Aggarwal said...

Wow!! Thanks a ton. This will surely be of great help.