Write a Program for a Singleton Class
Hi All,
I am not sure if you all know about "Singleton" class program in java or not. Well, in brief for those who don't know, it is a class that lets only one object to be created always. The basic approach being used is just making the constructor of the class as "private"
I am not sure if you all know about "Singleton" class program in java or not. Well, in brief for those who don't know, it is a class that lets only one object to be created always. The basic approach being used is just making the constructor of the class as "private"
/* Singleton Program **/ class Singleton{ private static Singleton singletonObj; private Singleton(){ } public void printMe(String val){ System.out.println("Singleton Test val="+val); } public static synchronized Singleton getInstance(){ if(singletonObj==null){ singletonObj=new Singleton(); } return singletonObj; } } /* Singleton class invoking program */ public class SingletonTest { public static void main(String[] args) throws Exception{ Singleton s1=Singleton.getInstance(); s1.printMe("1"); Singleton s2=Singleton.getInstance(); s2.printMe("2"); } }Now here goes my actual question, if I put a constraint to modify the above "Sinlgleton" class in such a way that the constructor access level is not "private" rather as "public" then how will you modify the "Singleton" class program so as to make below program working. It should show proper message like "Object -2 cannot be created" instead of printing output as
Singleton Test val=1
Singleton Test val=2
/* Singleton Program **/ class Singleton{ private static Singleton singletonObj; [B]public [/B]Singleton(){ } public void printMe(String val){ System.out.println("Singleton Test val="+val); } public static synchronized Singleton getInstance(){ if(singletonObj==null){ singletonObj=new Singleton(); } return singletonObj; } } /* Singleton class invoking program */ public class SingletonTest { public static void main(String[] args) throws Exception{ [B] Singleton s1=new Singleton(); s1.printMe("1"); Singleton s2=new Singleton(); s2.printMe("2");[/B] } }I have already given so much information in it, now just use little of Java knowledge and your brain how to handle this scenario.
0