Singlton

While writing the Singleton class I would consider these things


  • Make the default constructor private.
  • Create a static and public getInstance method returning the object of the singleton class.
  • Make the class final.
  • Implement the Cloneable interface.
  • Override the clone method to throw the CloneNotSupportedException.

package test.patterns;
public final class Singlton implements Cloneable {

private static Singlton singlton = null;
private Singlton(){}

public static Singlton getInstance(){
    if(singlton == null){
        singlton = new Singlton();
    }
    return singlton;
}


    protected Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException ("I do not allow to clone, this is SINGLTON");
    }

}
used Java2html to format the code

The other good type I read in the "Spring in Action" book
package test.patterns;

public class SingltonInner {

  private SingltonInner(){}
  
  private static class InnerSingltonInstance{
    static SingltonInner singlton = new SingltonInner();
  }
  
  public static SingltonInner getInstance(){
    return InnerSingltonInstance.singlton;
  }
}









Java2html





No comments:

Followers