单例模式(三种方法)

单例模式的结构:

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.什么情况下用单例模式

 使用单例模式有一个必要条件:在一个系统要求一个类只有一个实例时才应当使用单例模式。

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