设计模式 -- 单例设计模式

Java编程语言中,单例模式(饿汉模式)应用的例子如下述代码所示:

  public class Singleton { 
     private final static Singleton INSTANCE = new Singleton();//Privateconstructor suppresses 
  private Singleton() {}
 
    // default public constructor 
  public static Singleton getInstance() {
        return INSTANCE;
    } 
}

Java编程语言中,单例模式(懒汉模式)应用的例子如下述代码所示 (此种方法只能用在JDK5及以后版本(注意 INSTANCE 被声明为 volatie),之前的版本使用“双重检查锁”会发生非预期行为[1]):

  public class Singleton { 
     private static volatile Singleton INSTANCE = null;
 
    // Private constructor suppresses 
    // default public constructor 
     private Singleton() {}
 
    //thread safe and performance  promote 
  public static  Singleton getInstance() { 
         if(INSTANCE == null){ 
              synchronized(Singleton.class){
                 //when more than two threads run into the first null check same time, to avoid instanced more than one time, it needs to be checked again.
                 if(INSTANCE == null){ 
 INSTANCE = new Singleton(); 
                    } 
                  } 
          } 
         return INSTANCE;
  } 
}

 

posted @ 2013-08-02 10:46  微风夜明  阅读(98)  评论(0编辑  收藏  举报