Java Singleton Pattern
To implement a Singleton pattern,
- This overcome the problem of private constructor , that is other class main method cant create object to present class with private constructor.
- This technique is used to create and use class reference of present class, having private constructor , or access content in private constructor using static method present in class having private constructor;
- this is a sample program to illustrate the singleton pattern;
class santha // 1st class
{
public static santha yes=null; // here santha is class name type
String gift;
private santha() // this is private constructor
{
gift="bike";
}
public static santha ask_minions() // this is reference (yes) of class santha and this only of type null only or if change type
{
if(yes==null)
{
yes=new santha();
}
return yes;
}
}
public class SAMPLE1 // 2nd class
{
public static void main(String []args)
{
santha amith=santha.ask_minions(); //here amith is reference of type class santha // here static method ask_minions() is called using syntax class_name.static_methos_name();
System.out.println(amith.gift);
}
}