Make a class immutable by following these guidelines :
    * ensure the class cannot be overridden - make the class final, or use static factories and keep constructors private
    * make fields private and final
    * force callers to construct an object completely in a single step, instead of using a no-argument constructor combined with subsequent calls to setXXX methods (that is, avoid the Java Beans convention)
    * do not provide any methods which can change the state of the object in any way - not just setXXX methods, but any method which can change state
    * if the class has any mutable object fields, then they must be defensively copied when passed between the class and its caller
   
How can we make a class Singleton
1) make the constructor private.
2)Override clone method and throw clone supported exception.
3) Have a public method that creates an new instance when the instance is null or returns the new one.
A) If the class is Serializable
  class Singleton implements Serializable
  { 
    private static Singleton instance;
    private Singleton()  {  }  
public static synchronized  Singleton getInstance()
          {
        if (instance == null)
            instance = new Singleton();
        return instance;
    }
    /**
If the singleton implements Serializable, then this
    * method must be supplied.
    */
    protected Object readResolve() {
        return instance;
    }
    /**
    This method avoids the object fro being cloned
    */
    public Object clone() {
        throws CloneNotSupportedException ;
        //return instance;
    }
 }
B) If the class is NOT Serializable
class Singleton
    {
    private static Singleton instance;
    private Singleton()  {  }  
public static synchronized  Singleton getInstance()
          {
        if (instance == null)
            instance = new Singleton();
        return instance;
    }
    /**
This method avoids the object from being cloned
    **/
    public Object clone() {
        throws CloneNotSupportedException ;
        //return instance;
    }
}
Monday, December 28, 2009
Subscribe to:
Post Comments (Atom)
 
No comments:
Post a Comment