Java中單例模式實現方法

/**
 * 1、懶漢,經常使用的寫法
 */
class LazySingleton{
    private static LazySingleton singleton;
    private LazySingleton(){
    }
    public static LazySingleton getInstance(){
        if(singleton==null){
            singleton=new LazySingleton();
        }
        return singleton;
    }  
}
/**
 * 2、惡漢,缺點:沒有達到lazy loading的效果
 */
class HungrySingleton{
    private static HungrySingleton singleton=new HungrySingleton();
    private HungrySingleton(){}
    public static HungrySingleton getInstance(){
        return singleton;
    }
}
/**
 * 3、靜態內部類 優勢:加載時不會初始化靜態變量INSTANCE,由於沒有主動使用,達到Lazy loading
 */
class InternalSingleton{
    private static class SingletonHolder{
        private final static  InternalSingleton INSTANCE=new InternalSingleton();
    }  
    private InternalSingleton(){}
    public static InternalSingleton getInstance(){
        return SingletonHolder.INSTANCE;
    }
}
/**
 * 4、枚舉,《Effective Java》做者推薦使用的方法,優勢:不只能避免多線程同步問題,並且還能防止反序列化從新建立新的對象
 */
public enum FacHelper {
    
    facHelper;
    
    private SqlSessionFactory factory;
    
    private FacHelper(){
        try {
            singletonOperation();
        } catch (IOException e) {
            e.printStackTrace();
        }
    };
    
     public void singletonOperation() throws IOException{ 
        //裝載配置文文件 
         String resource = "Configuration.xml";
            Reader reader = Resources.getResourceAsReader(resource);
            Properties prop = new Properties();
            prop.put("username", "zxf");
            prop.put("password", "zxf");
            //產生工廠
            factory = new SqlSessionFactoryBuilder().build(reader, prop);
            //測試驗證此方法只執行一次
            System.err.println("55555555555555555555555555555555");
     }
 
    public SqlSessionFactory getFactory() {
        return factory;
    }
 
    public void setFactory(SqlSessionFactory factory) {
        this.factory = factory;
    }
}
/**
 *5、 雙重校驗鎖,在當前的內存模型中無效
 */
class LockSingleton{
    private volatile static LockSingleton singleton;
    private LockSingleton(){}
    
    //詳見:http://www.ibm.com/developerworks/cn/java/j-dcl.html
    public static LockSingleton getInstance(){
        if(singleton==null){
            synchronized(LockSingleton.class){
                if(singleton==null){
                    singleton=new LockSingleton();
                }
            }
        }
        return singleton;
    }
    
}
 html

相關文章
相關標籤/搜索