隨筆-19  評論-2  文章-1  trackbacks-0

           復習

           

          其中登記式注冊單例模式:

          import java.util.*;

          class Single{

                 private static HashMap hashmap = new HashMap();

                 private int number = 0;

                 static{

                        Single single = new Single();

                        hashmap.put(single.getClass().getName(),single);

                 }

                 private Single(){}

                 public static Single getInstance(String name){

                        if(name == null){

                               name = "Single";

                        }

                        if(hashmap.get(name) == null){

                               try{

                                      hashmap.put(name,Class.forName(name).newInstance());

                               }catch(Exception e){

                                      System.out.println(e.getMessage());

                               }

                        }

                        return (Single)hashmap.get(name);

                 }

                 public void fun(){

                        number++;

                        System.out.println("the is the single fun :" + number);

                 }

          }

           

          他的另外一個做法是同過繼承,通過父類來注冊子類的對象:

          代碼如:

          class SingleChild extends Single{

                 public SingleChild(){}

                 public static SingleChild getInstance(){

                        return (SingleChild)Single.getInstance("SingleChild");

                 }

                 public void fun(){

                        System.out.println("singlechild");

                 }

          }

          當它要這樣做之后就破壞了父類,因為子類要調用父類的構造子函數,所以父類的構造子函數就不能夠為私有的,這就破壞單例模式的優點。

          posted on 2005-07-30 21:04 sky 閱讀(84) 評論(0)  編輯  收藏

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


          網站導航:
           
          主站蜘蛛池模板: 金湖县| 灵璧县| 苍山县| 南陵县| 腾冲县| 崇明县| 永宁县| 八宿县| 静乐县| 长岛县| 民和| 滨海县| 偃师市| 仙桃市| 日喀则市| 兴安盟| 阿巴嘎旗| 茶陵县| 蒙城县| 集贤县| 五家渠市| 清涧县| 金沙县| 高唐县| 长垣县| 鄂尔多斯市| 易门县| 永春县| 石渠县| 五常市| 万州区| 梨树县| 柯坪县| 安溪县| 江北区| 西乡县| 杭锦后旗| 清流县| 民县| 常德市| 崇阳县|