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

          單例模式

          Posted on 2007-05-28 15:47 change 閱讀(225) 評論(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());
           }
          }

            

          主站蜘蛛池模板: 六盘水市| 澜沧| 江安县| 漠河县| 玉树县| 永修县| 大足县| 仲巴县| 庆城县| 阿城市| 湖北省| 南宁市| 临沂市| 社旗县| 鄱阳县| 伊春市| 高碑店市| 嘉定区| 霍城县| 布拖县| 台前县| 巩义市| 柳林县| 万盛区| 长岛县| 清苑县| 壤塘县| 扎兰屯市| 通榆县| 合山市| 林口县| 进贤县| 自贡市| 宁晋县| 上饶县| 新宁县| 丹寨县| 富平县| 隆子县| 巴楚县| 永德县|