Tuesday, November 22, 2011

Design Pattern -- Singleton

Singleton Design patttern is used to control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation arises.To prevent direct instantiation we create a private default constructor,so that other classes can’t create  a new Instance. The following few lines of code demonstrates a way of creating a singleton object.

public class SingletonObject
  {
     private static SingletonObject ref;
     
     private SingletonObject()
      {
      }
    
    public static SingletonObject getSingletonObject()
      {
    if(ref == null)
{
  ref = new SingletonObject();
  return ref;
}
      }

   public Object clone() throws CloneNotSupportedException
{
throws new CloneNotSupportedException();
}
}

No comments:

Post a Comment