隨筆 - 40, 文章 - 0, 評論 - 20, 引用 - 0
          數據加載中……

          23種面向對象的設計模式----Singleton模式

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

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

          1,如果你要把這個數字永久保存到數據庫,你可以在不修改單態接口的情況下方便的做到。
          下面是一個簡單的示例程序:
          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);
           }  
          }
          我們還可以在這個基礎上做一個擴展,如從上面例子中的TestSingleton類擴展出多個子類,在

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

          -----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)  編輯  收藏


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


          網站導航:
           
          主站蜘蛛池模板: 新民市| 邵武市| 巨鹿县| 义乌市| 宜川县| 东乌珠穆沁旗| 康马县| 绥宁县| 石家庄市| 二连浩特市| 台安县| 来安县| 衡阳县| 吉林省| 兴安盟| 双牌县| 鹿邑县| 电白县| 溆浦县| 呼玛县| 新竹市| 西和县| 义马市| 漳州市| 南投县| 锦屏县| 新民市| 高青县| 桑日县| 喀喇沁旗| 上高县| 红原县| 竹溪县| 富蕴县| 鞍山市| 河北区| 昌平区| 大理市| 海门市| 科技| 白河县|