Singleton design pattern is most commonly used design pattern across all Java/J2EE applications. This design pattern is used for controlling the creation of number of instances for a specific class. Remember controlling instances is per 'Class Loader' and not for JVM. As you know JVM can have more than one class loader.
Version 1 :
public class DateTimeUtil{
// Declare static instance, that means one for a class (Not for instance )
public static DateTimeUtil singleton=null;
// Create a method , first time creates the instance, for every next subsequent calls, will not create a new instance.
public DateTimeUtil getInstance(){
// Create instance for very first time.
if(singleton==null){
singleton = new DateTimeUtil();
}
return singleton;
}
}
Versiont 2
public class DateTimeUtil{
// Declare and create instance when class loaded itself.
public static final DateTimeUtil singleton=new DateTimeUtil();
public DateTimeUtil getInstance(){
return singleton;
}
}
Version 1 :
public class DateTimeUtil{
// Declare static instance, that means one for a class (Not for instance )
public static DateTimeUtil singleton=null;
// Create a method , first time creates the instance, for every next subsequent calls, will not create a new instance.
public DateTimeUtil getInstance(){
// Create instance for very first time.
if(singleton==null){
singleton = new DateTimeUtil();
}
return singleton;
}
}
Versiont 2
public class DateTimeUtil{
// Declare and create instance when class loaded itself.
public static final DateTimeUtil singleton=new DateTimeUtil();
public DateTimeUtil getInstance(){
return singleton;
}
}
No comments:
Post a Comment