隨筆 - 40, 文章 - 0, 評論 - 20, 引用 - 0
          數(shù)據(jù)加載中……

          23種面向?qū)ο蟮脑O(shè)計模式----Singleton模式

            Singleton模式為單態(tài)模式或者叫孤子模式,保證一個類只有一個實例,并提供一個訪問它的全局訪問點。
            Singleton模式的使用范圍比較廣泛,對于一些類來說,只有一個實例是很重要的。比如,你要論壇中

          的帖子計數(shù)器,每次瀏覽一次需要計數(shù),單態(tài)類能否保持住這個計數(shù),并且能synchronize的安全自動加

          1,如果你要把這個數(shù)字永久保存到數(shù)據(jù)庫,你可以在不修改單態(tài)接口的情況下方便的做到。
          下面是一個簡單的示例程序:
          package Singleton;
          public class TestSingleton { 
           private static TestSingleton  testSingleton = null;
           protected int  count = 0; 
           public static synchronized  TestSingleton getInstance(){
             if( testSingleton ==   null)
              testSingleton = new TestSingleton();
             return testSingleton;
           }
           public void addCount(){
            count ++;
           }
           public void showCount(){
            System.out.println("count :"+count);
           }  
          }
          我們還可以在這個基礎(chǔ)上做一個擴(kuò)展,如從上面例子中的TestSingleton類擴(kuò)展出多個子類,在

          getInstance方法中控制要使用的是哪個子類,具體實現(xiàn)代碼如下:

          -----TestSingleton.java
          package Singleton;
          public class TestSingleton { 
           private static TestSingleton  testSingleton = null;
           protected int  count = 0; 
           public static synchronized  TestSingleton getInstance(){
             if( testSingleton ==   null)
              testSingleton = new SubTestSingleton ();
             return testSingleton;
           }
           public void addCount(){
            count ++;
           }
           public void showCount(){
            System.out.println("TestSingleton count :"+count);
           }  
          }

          -----SubTestSingleton.java
          public class SubTestSingleton extends TestSingleton{
           public void showCount(){
            System.out.println("SubTestSingleton count :"+count);
           }
          }

          <以上為個人見解,歡迎大家評論!>

          posted on 2005-11-13 15:54 月亮 閱讀(665) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 三都| 政和县| 罗定市| 义马市| 城固县| 衡水市| 沙雅县| 手游| 壤塘县| 乐昌市| 商水县| 江阴市| 东光县| 吴忠市| 仁化县| 沙田区| 慈溪市| 万盛区| 蛟河市| 富顺县| 峨山| 建阳市| 扶风县| 苏尼特右旗| 普格县| 综艺| 铜山县| 灌南县| 临澧县| 武陟县| 华坪县| 三原县| 延长县| 奉节县| 陆河县| 梅河口市| 大庆市| 阿鲁科尔沁旗| 五莲县| 象山县| 新竹县|