Java单例模式

WINCOL 2010-05-07

1、使用同步方法:

private static Singleton instance;

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

2、放弃同步,使用静态变量:

private static Singleton instance = new Singleton();

public static Singleton getInstance(){
    return instance;
}

3、比较新颖的写法:

public    class  Singleton  {    

    static    class  SingletonHolder  {    
      static  Singleton instance  =    new  Singleton();    
  }     

    public    static  Singleton getInstance()  {    
      return  SingletonHolder.instance;    
  }     

}

相关推荐

ganyouxianjava / 0评论 2012-05-31