Friday, December 31, 2010
Sunday, December 5, 2010
Design Patterns -Singleton Pattern
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