爱生活爱睡觉爱大笑

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  0 随笔 :: 2 文章 :: 0 评论 :: 0 Trackbacks
Initialization on demand holder idiom
public class Singleton {
   
// Protected constructor is sufficient to suppress unauthorized calls to the constructor
   protected Singleton() {}
 
   
/**
    * SingletonHolder is loaded on the first execution of Singleton.getInstance() 
    * or the first access to SingletonHolder.INSTANCE , not before.
    
*/

   
private static class SingletonHolder 
     
private final static Singleton INSTANCE = new Singleton();
   }

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

 }


Traditional simple way
public class Singleton {
   
public final static Singleton INSTANCE = new Singleton();
 
   
// Protected constructor is sufficient to suppress unauthorized calls to the constructor
   protected Singleton() {}
 }


Java 5 solution
public class Singleton {
   
private static volatile Singleton INSTANCE;
 
   
// Protected constructor is sufficient to suppress unauthorized calls to the constructor
   protected Singleton() {}
 
   
public static Singleton getInstance() {
      
if (INSTANCE == null{
         
synchronized(Singleton.class{
           
if (INSTANCE == null)
             INSTANCE 
= new Singleton();
         }

      }

      
return INSTANCE;
   }

}

The "Double-Checked Locking is Broken" Declaration.

The Enum-way
public enum Singleton {
   INSTANCE;
 }

posted on 2008-10-30 14:16 重回疯人院 阅读(157) 评论(0)  编辑  收藏 所属分类: Pattern

只有注册用户登录后才能发表评论。


网站导航: