ITeye博客

设计模式快速参考-单例模式

gurudk · 2008-12-06 06:46 · 模式 · 设计模式 · 多线程 · Markdown

class Singleton{

   private Singleton(){
   }

   private static Singleton singleton = null;

   public static Singleton getInstance(){
      if(null == singleton){
         singleton = new Singleton();
      }
      return singleton;
   }
   public String otherOperation(){
      //方法实现
   }
}

 

Client:

 

String str = Singleton.getInstance().otherOperation();

 

多线程时使用 double-check 模式确保线程安全:

 

class Singleton{
   
   private Singleton(){
   }
   private static Singleton singleton = null;
   public static Singleton getInstance(){
      if(null == singleton)
         sychronized (Singleton.class){
          if(null == singleton){
             singleton = new Singleton();
          }
       }
    }
    return singleton;
  }
}

评论(2)

  1. #2 楼 · gurudk · 2009-02-01 21:09

    ws715 writes:

    缺一个私用的构造函数 private Singleton(){}

    You are right thanks!

  2. #1 楼 · ws715 · 2009-02-01 16:12

    缺一个私用的构造函数 private Singleton(){}

评论功能维护中,当前仅展示历史评论。