posts - 29, comments - 0, trackbacks - 0, articles - 0
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          單例模式

          Posted on 2007-05-28 15:47 change 閱讀(228) 評論(0)  編輯  收藏

          如何使一個類只能夠有一個對象 呢,我們知道這樣的類的構造函數是必須為私有的,否則用戶就可以任意多的生產該類的對象了。那么具體應該怎么實現呢,有兩種方式:一種是給類一個該類型的 static 成員對象,每次都調用一個get方法返回該對象,這也就是所謂的餓漢模式;

          public class EagerSingleton {
           String name;
           private static final EagerSingleton m_instance = new EagerSingleton();
           
           private EagerSingleton()
           {
            name ="wqh";
           }
           public static EagerSingleton getInstance()
           {
            return m_instance;
           }
           
           public static void main(String[] args) {
            EagerSingleton es ;
            es = EagerSingleton.getInstance();
            System.out.println(es.name);
           }
          }

          在有一種呢就是在該類型里面先聲明一個對象,如何通過一個同步的static方法每次返回同一個 對象,這也就是 所謂的懶漢模式,如下:

          public class LazySingleton {
           private static LazySingleton m_instance = null;
           private LazySingleton()
           {
           
           }
           synchronized public  static LazySingleton getInstance()
           {
            if(m_instance == null)
            {
             m_instance = new LazySingleton();
            }
            return m_instance;
           }
           
           public static void main(String[] args) {
            LazySingleton ls;
            ls = LazySingleton.getInstance();
            System.out.println(ls.getClass());
           }
          }

            

          主站蜘蛛池模板: 民权县| 泰和县| 鸡泽县| 文山县| 兴和县| 兰考县| 东光县| 郓城县| 澎湖县| 和平县| 韩城市| 疏附县| 永城市| 清苑县| 浑源县| 铁岭市| 襄垣县| 天镇县| 邢台市| 涿鹿县| 澎湖县| 彝良县| 龙门县| 武陟县| 海安县| 青龙| 乐业县| 含山县| 嘉义县| 开平市| 嵊泗县| 康乐县| 玛曲县| 铜山县| 竹北市| 临海市| 商南县| 齐河县| 碌曲县| 安国市| 德惠市|