Singleton Pattern 的几种方式

public class Singleton {
    private final static Singleton instance = new Singleton();
    // Private constructor suppresses generation of a (public) default constructor

    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
   }
}
public class Singleton {
  private static Singleton instance;
  // Private constructor suppresses generation of a (public) default constructor

  private Singleton() {}

  public static synchronized Singleton getInstance() {
    if(instance == null) {
      instance = new Singleton();
    }

    return instance;
  }
}
public class Singleton {
  // Private constructor suppresses generation of a (public) default constructor
  private Singleton() {}
  private static class SingletonHolder {
    private static Singleton instance = new Singleton();
  }

  public static Singleton getInstance() {
    return SingletonHolder.instance;
  }
}
public class Singleton {
  private volatile static Singleton instance;
  // Private constructor suppresses generation of a (public) default constructor

  private Singleton() {}

  public static Singleton getInstance() {
    if(instance == null) {
      synchronized(Singleton.class) {
        if(instance == null) {
          instance = new Singleton();
        }
      }
    }
    return instance;
  }
}
By javafuns on May 17, 2007 at 23:54 · Views: 626 · Permalink · RSS
Categorized in: Design Patterns, Java · Tagged with: ,
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Leave a Reply


  • Highest Rated

  • My PicasaPhotos

    IMG_0522.JPG

    IMG_0635.JPG

    IMG_0584.JPG

  • RSS My del.icio.us

  • My RSS