單例模式(三種方法)

單例模式的結構:

a)單例模式的特點:

    單例類只能有一個實例;

    單例類必須自己創建自己的唯一的實例;

    單例類必須給所有其他對象提供這個實例;

b)餓漢式單例類(不可被繼承)

        public class EagerSingleton {

      private static final EagerSingletone_s=new EagerSingleton ();

      private EagerSingleton (){}

      public  static  EagerSingleton getInstance(){

           returne_s;

      }

  }

c)懶漢式單例類(不可被繼承)

   public class LazySingleton {

      private static LazySingletonl_s=null;

      private LazySingleton(){}

      synchronized public static LazySingleton getInstance(){

          if(l_s==null)

                l_s=new LazySingleton();

          returnl_s;

      }

  }

    方法中添加了線程控制屬性,目的是爲了當在多線程程序中使用單例類時,由於在最初啓動單例

  類時的出現同步問題而加上synchronized屬性

 d)登記式單例類

  爲餓漢和懶漢單例類不能被繼承而設立的。

  public class RegSingleton {

     private static HashMapm_registry=new HashMap();

     static{

           RegSingleton x =new RegSingleton();

           m_registry.put(x.getClass().getName(), x);

     }

     protected RegSingleton(){}

     public static RegSingleton getInstance(String name){

           if(name ==null){

                 name ="Test.RegSingleton";

           }

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

                 try{

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

                 }catch(Exception e){

                       System.out.println("Error happened");

                 }

           }

           return(RegSingleton)(m_registry.get(name));

     }

     public String about(){

           return "hello, I am RegSingleton";

     }

 

}

public class RegSingletonChild extends RegSingleton {

     public RegSingletonChild(){}

     static public RegSingletonChild getInstance(){

           return (RegSingletonChild)RegSingleton.getInstance("Test.RegSingletonChild");

     }

     public String about(){

           return "hello, I am RegSingletonChild";

     }

}

2.什麼情況下用單例模式

 使用單例模式有一個必要條件:在一個系統要求一個類只有一個實例時才應當使用單例模式。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章