Creational Patterns - Singleton Pattern(A class distributes the only instance of itself)
When to use ?
There are some instances in the application where we have to use just one instance of a particular class.
Below Example, Display and FDisplay Class having printwithDateandTime method , it will print with currentTime
APPROACH 1:
We use Singleton pattern for this and instantiate the Display when the first request hits
import java.sql.Timestamp;
/**
*
* @author R.Amirtharj
*/
public class Display {
// singleton - pattern
private static Display display = null;
public static Display getDisplay() {
return display;
}
// initialises the display, creates an object
public static void initialize() {
if(display == null) display = new Display();
}
/**
* Private constructor
*/
private Display() {
display = this;
}
public void printwithDateandTime(String strMsg)
{
System.out.println(strMsg+" Date:"+new Timestamp(System.currentTimeMillis()));
}
}
APPROACH 2:
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.
import java.sql.Timestamp;
/**
*
* @author R.Amirtharj
*/
public final class FDisplay {
public static void printwithDateandTime(String strMsg)
{
System.out.println(strMsg+" Date:"+new Timestamp(System.currentTimeMillis()));
}
}
Main Class:
/**
*
* @author R.Amirtharaj
*/
public class Demo {
public static void main(String arg[])
{
// Approach 1
Display.initialize();
Display.getDisplay().printwithDateandTime(" Singleton test Approach 1 ");
// Approach 1
FDisplay.printwithDateandTime(" Singleton test Approach 2");
}
}
Note : 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.
No comments:
Post a Comment