Monday, November 1, 2010

Singleton or Abstract Constructor Pattern

Singleton Class !!! As the name suggests there some thing single related to these type of classes. Single object ... just one object can be created and in order to achieve that we need to code appropriately. Lets see a sample code or rather an attempt to create class singleton. Some new concepts (even by java compiler and run time environment) are illustrated.


public class Employee {


Employee e = null;

Employee(){

if(e == null)
e = new Employee();

return e;

}
}



  1. We know constructor don't have any return type but it can still return object of the class itself. Interesting may be there is Abstract Constructor Pattern and this is the basis. Some one will discover soon.
  2. Interviewee confirmed thrice with confidence that this code not only compiles but at run time it doesn't end up in recursion calling constructor of class again from constructor again with a condition that is not on static variable.



No comments:

Post a Comment