首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> J2SE

Java 私有建構子實戰(一):HibernateSessionFactory 單例模式實現分析

     編輯:J2SE

類結構概覽

HibernateSessionFactory 採用經典單例模式,透過 ThreadLocal 管理每執行緒的 Session,核心欄位皆為 private static:

  • CONFIG_FILE_LOCATION:Hibernate 設定檔路徑
  • threadLocal:儲存當前執行緒的 Session
  • cfg:Configuration 單例
  • sessionFactory:SessionFactory 單例

關鍵方法

currentSession()

public static Session currentSession() throws HibernateException {
    Session session = (Session) threadLocal.get();
    if (session == null) {
        if (sessionFactory == null) {
            try {
                cfg.configure(CONFIG_FILE_LOCATION);
                sessionFactory = cfg.buildSessionFactory();
            } catch (Exception e) { /* 錯誤處理 */ }
        }
        session = sessionFactory.openSession();
        threadLocal.set(session);
    }
    return session;
}

雙重檢查鎖定模式確保 SessionFactory 僅建立一次,並綁定到當前執行緒。

私有建構子

private HibernateSessionFactory() {}

防止外部直接實例化,強制使用靜態方法 currentSession()、closeSession() 管理 Session 生命週期。

設計優勢

  • 執行緒安全:每個執行緒擁有獨立 Session。
  • 延遲初始化:首次調用時才建立 SessionFactory。
  • 封裝性:隱藏建構細節,統一存取點。

本文來自編程入門網:原文連結

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved