Sunday, December 5, 2010

Design Patterns -Singleton Pattern

his is one of the most commonly used patterns. There are some instances in the application where we have to use just one instance of a particular class. This Pattern is the Common Creational Pattern in terms of Creation. In Case of Multiple Threading, Synchronization is Necessary. So Object Creation should be in Synchronization Block.
For Eg: LogSingleton.java

import java.util.*;
public class LogSingleton
{
private static LogSingleton instance=null;

private LogSingleton()
{
instance=this;
}

public static LogSingleton getLogger()
{
if (instance == null)
{
//In Case of MultiThreading Logging
synchronized(LogSingleton.class)
{
instance = new LogSingleton();
}
}
return instance;
}
public void logMsg(String msg)
{
System.out.println("Msgasd:"+msg);
}
}

Difference between static class and static method approaches:
One question which a lot of people have been asking me. What’s the difference between a singleton class and a static class? The answer is static class is one approach to make a class “Singleton”.

We can create a class and declare it as “final” with all the methods “static”. In this case, you can’t create any instance of class and can call the static methods directly.

Example:

final class Logger {
//a static class implementation of Singleton pattern
static public void logMessage(String s) {
System.out.println(s);
}
}// End of class

//==============================
public class StaticLogger {
public static void main(String args[]) {
Logger.logMessage("This is SINGLETON");
}
}// End of class