GeekInterview.com
   Home |  Tech FAQ  |   Interview Questions |  Placement Papers |  Tech Articles |  Learn |  Freelance Projects |  Online Testing |  Geeks Talk |  Job Postings |  Knowledge Base | Site Search |  Add/Ask Question

  GeekInterview.com  >  Interview Questions  >  J2EE  >  Java Patterns

 Print  |  
Question:  What is singleton pattern ??



December 12, 2006 05:11:33 #2
 hi_goura   Member Since: December 2006    Total Comments: 6 

RE: What is singleton pattern ??
 
Singleton pattern is a design pattern by which we cannot create more than one instance of the class. For a fresh request to get an instance, a new instance will be returned. And further requests will return you the referenceto the earlier one. There is no keyword singleton to make your class as "Singleton Class". You have to design your class accordingly. First of all make the default constructor private and don't give any other constructor to restrict creation of multiple instances from outside of your class. Have a public static method that returns you the reference to the same class (this is called Factory method). Have a class-level (static) private variable whose data-type is same class. Inside the static method, check if the static variable is null then create a new object, assign that to the static variable and return it. If that is not-null, that means this is not the first request, return the same static variable. Now If someone wants an instance of your class, (s)he must call YourClass.staticMethod(). No other option. Thanks-Gourahari
     

 

Back To Question