Singleton Pattern
Singleton Pattern:
The singleton design
pattern deals with one and only one instance of an object that encapsulates the
control of the object from a common place. There are various ways of achieving
this pattern.
For example, create an exception that is thrown by a class if the class is instantiated more than once. Next declare a boolean variable and make it static so that it can be shared among all the instances of a class. Initialize this static variable inside the constructor of this class. The constructor would throw an exception if it is initialized second time. It is the best technique of using the singleton pattern. But take care to set the variable whenever destroying during the finalize method call.
Another approach of creating Singleton method includes a static method and private constructor in a class. Declaring the constructor as private ensures that the instance variable can be created only from inside the method of the class. The static method sets the variable as boolean that indicates the creation of the instance and returns an instance.
Benefits: Singleton pattern controls access to unique instances, reduce name space, permits a variable number of instances, allows refinement of operations and representations, and provides more flexibility than class operations.
Usage: These are used in those places where there is only one instance of a class. The Singleton pattern is mostly used in multi-threaded applications. Singleton patterns are often used as global variables because the global variables permit allocation and initialization whenever required. They don't permit to pollute the global namespace with unnecessary variables.
package singleton; import org.apache.log4j.Priority; import java.util.GregorianCalendar; import java.text.SimpleDateFormat; import java.io.FileOutputStream; import java.util.Properties; import java.io.PrintStream; import java.io.InputStream; import java.io.IOException; public class Logger { private String fileName; private Properties properties; private Priority priority; private Logger() { logger = this; } public int getRegisteredLevel() { int i = 0; try { InputStream inputstream = getClass().getResourceAsStream("Logger.properties"); properties.load(inputstream); inputstream.close(); i = Integer.parseInt(properties.getProperty("logger.registeredlevel")); if(i < 0 || i > 3) i = 0; } catch(Exception exception) { System.out.println("Logger: Failed in the getRegisteredLevel method"); exception.printStackTrace(); } return i; } private String getFileName(GregorianCalendar gc) { SimpleDateFormat dateFormat1 = new SimpleDateFormat("dd-MMM-yyyy"); String dateString = dateFormat1.format(gc.getTime()); String fileName = "C:\\prashant\\patterns\\log\\PatternsExceptionLog-" + dateString + ".txt"; return fileName; } public void logMsg(Priority p, String message) { try { GregorianCalendar gc = new GregorianCalendar(); String fileName = getFileName(gc); FileOutputStream fos = new FileOutputStream(fileName, true); PrintStream ps = new PrintStream(fos); SimpleDateFormat dateFormat2 = new SimpleDateFormat("EEE, MMM d, yyyy 'at' hh:mm:ss a"); ps.println("<"+dateFormat2.format(gc.getTime())+">["+message+"]"); ps.close(); } catch (IOException ie) { ie.printStackTrace(); } } public static void initialize() { logger = new Logger(); } // singleton - pattern private static Logger logger; public static Logger getLogger() { return logger; } } |
Difference between static class and static method approaches: One question
that comes to most of the people's mind is that " What?s the difference between
a static class and a singleton class?" The answer is static class is one of the approaches
that makes a class ?Singleton?.
We can create and declare a class as ?final? simply by declaring all its methods
as ?static?. In this case,
you can call the static methods directly but can?t create any instance of class.
Example:
final class Logger { //implementation of a static class of a Singleton pattern static public void logMessage(String s) { System.out.println(s); } } public class StaticLogger { public static void main(String args[]) { Logger.logMessage("This is SINGLETON"); } } |
The advantage of this static approach is that it?s easier to use. The disadvantage of course is that if in future you do not want the class to be static anymore, you will have to do a lot of recoding.