消化单例设计模式(Java版本)

Valeria00D 7年前
   <p><img src="https://simg.open-open.com/show/d5115acd44ec9babc4f8b85d4eec30b6.png"></p>    <p>设计模式在软件开发人员中非常流行。设计模式是一套代码设计经验的总结。单例模式是Java 创建型设计模式 中的一种。</p>    <h2>单例模式的目的是什么?</h2>    <p>单例类的目的是为了控制对象的创建,限制对象的数量只能是1。单例只允许有一个入口可以创建这个类的实例。</p>    <p>由于只有一个单例实例,所以单例中任何字段的初始化都应该像静态字段一样只发生一次。当我们需要控制一些资源比如数据库连接或者sokets等时,单例就非常有用。</p>    <p>听起来好像是一个非常简单的设计模式,但是当要具体实现的时候,它会带来许多实践问题。怎么实现单例模式在开发者之间一直是一个有争议的话题。在这里我们将讨论怎样创建一个单例类来满足它的需求:</p>    <p>限制类的创建并且保证在java虚拟机中只有一个该类的实例存在。</p>    <p>我们用java创建一个单例类,并在不同的条件下测试。</p>    <h2>使用Java创建一个单例类</h2>    <p>为了实现单例类,最简单的方式就是将该类的构造函数定义为私有方法。</p>    <ul>     <li><strong>1、饿汉式初始化:</strong></li>    </ul>    <p>在饿汉模式中,单例类的实例在加载这个类的时候就被创建,这是创建单例类最简单的方法。</p>    <p>将单例类的 构造函数 定义为私有方法,其他类就不能创建该类的实例。取而代之的是通过我们提供的静态方法入口(通常命名为 <em>getInstance()</em> )来获取该类实例。</p>    <pre>  <code class="language-java">public class SingletonClass {        private static volatile SingletonClass sSoleInstance = new SingletonClass();        //私有构造函数      private SingletonClass(){}        public static SingletonClass getInstance() {          return sSoleInstance;      }  }</code></pre>    <p>这种方法有一个缺点。这里有可能我们不会使用这个实例,但是单例的实例还是会被创建。如果你的单例类在创建中需要建立同数据库的链接或者创建一个socket时,这可能是一个严重的问题。因为这可能会导致内存泄漏。解决办法是当我们需要使用时再创建单例类的实例。这就是所谓的懒汉式初始化。</p>    <ul>     <li><strong>2、懒汉式初始化:</strong></li>    </ul>    <p>与 <strong>饿汉式初始化</strong> 不同,这里我们由 <em>getInstance()方法自己</em> 初始化单例类的实例。这个方法会检查该类是否已经有创建实例?如果有,那么 <em>getInstance()</em> 方法会返回已经创建的实例,否则就在JVM中创建一个该类的实例并返回。这种方法就称为懒汉式初始化。</p>    <pre>  <code class="language-java">public class SingletonClass {        private static SingletonClass sSoleInstance;        private SingletonClass(){}  //private constructor.        public static SingletonClass getInstance(){          if (sSoleInstance == null){ //if there is no instance available... create new one              sSoleInstance = new SingletonClass();          }            return sSoleInstance;      }  }</code></pre>    <p>我们知道在Java中如果两个对象相同,那么他们的哈希值也应该相等。那么我们来测试一下。如果上面的单例实现是正确的,那么下面的测试代码应该返回相同的哈希值。</p>    <pre>  <code class="language-java">public class SingletonTester {     public static void main(String[] args) {          //Instance 1          SingletonClass instance1 = SingletonClass.getInstance();            //Instance 2          SingletonClass instance2 = SingletonClass.getInstance();            //now lets check the hash key.          System.out.println("Instance 1 hash:" + instance1.hashCode());          System.out.println("Instance 2 hash:" + instance2.hashCode());       }  }</code></pre>    <p>下面是两个实例哈希值的log输出。</p>    <p><img src="https://simg.open-open.com/show/69d810a20e259b019fa522d1542c970c.png"></p>    <p>我们可以看到两个实例的哈希值是相等的。所以,这意味着以上代码完美的实现了一个单例。是吗???? <strong>不是。</strong></p>    <h2>如果使用Java的反射API呢?</h2>    <p>在上面的单例类中,通过使用反射我们可以创建多个实例。如果你不知道 Java反射API ,Java反射就是在代码运行时检查或者修改类的运行时行为的过程。</p>    <p>我们可以在运行过程中将单例类的构造函数的可见性修改为public,从而使用修改后的构造函数来创建新的实例。运行下面的代码,看看我们的单例是否还能幸存?</p>    <pre>  <code class="language-java">public class SingletonTester {     public static void main(String[] args) {          //创建第一个实例          SingletonClass instance1 = SingletonClass.getInstance();            //使用Java反射API创建第二个实例.          SingletonClass instance2 = null;          try {              Class<SingletonClass> clazz = SingletonClass.class;              Constructor<SingletonClass> cons = clazz.getDeclaredConstructor();              cons.setAccessible(true);              instance2 = cons.newInstance();          } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) {              e.printStackTrace();          }            //现在来检查一下两个实例的哈希值          System.out.println("Instance 1 hash:" + instance1.hashCode());          System.out.println("Instance 2 hash:" + instance2.hashCode());     }  }</code></pre>    <p>这里是两个实例哈希值的log输出。</p>    <p><img src="https://simg.open-open.com/show/f8a9ca46a8a311dbad19631b6b43d1e4.png"></p>    <p>哈希值并不相等</p>    <p>两个实例的哈希值并不相等。这清晰的说明我们的单例类并不能通过这个测试。</p>    <p>解决方法:</p>    <p>为了阻止因为反射导致的测试失败,如果构造函数已经被调用过还有其他类再次调用时我们必须抛出一个异常。来更新一下 <em>SingletonClass.java</em> 。</p>    <pre>  <code class="language-java">public class SingletonClass {        private static SingletonClass sSoleInstance;        //私有构造方法      private SingletonClass(){            //阻止通过反射的API调用.          if (sSoleInstance != null){              throw new RuntimeException("Use getInstance() method to get the single instance of this class.");          }      }         public static SingletonClass getInstance(){          if (sSoleInstance == null){ //如果还没可用的实例。。。。创建一个              sSoleInstance = new SingletonClass();          }            return sSoleInstance;      }  }</code></pre>    <h2>我们的单例线程安全吗?</h2>    <p>如果有两个线程几乎在同时初始化我们的单例类,会发生什么?我们一起来测试一下下面的代码,这段代码中两线程几乎同时创建并且都调用 <em>getInstance()</em> 方法。</p>    <pre>  <code class="language-java">public class SingletonTester {     public static void main(String[] args) {          //Thread 1          Thread t1 = new Thread(new Runnable() {              @Override              public void run() {                  SingletonClass instance1 = SingletonClass.getInstance();                  System.out.println("Instance 1 hash:" + instance1.hashCode());              }          });            //Thread 2          Thread t2 = new Thread(new Runnable() {              @Override              public void run() {                  SingletonClass instance2 = SingletonClass.getInstance();                  System.out.println("Instance 2 hash:" + instance2.hashCode());              }          });            //start both the threads          t1.start();          t2.start();     }  }</code></pre>    <p>如果你运行这段代码很多次,你会发现有时两个线程创建了不同的实例:</p>    <p><img src="https://simg.open-open.com/show/82efac568829c7bbcf476c280d33f073.png"></p>    <p>哈希值并不相等</p>    <p>这意味着我们的单例是 <strong>线程不安全的</strong> 。如果两个线程同时调用我们的 <em>getInstance()</em> 方法,那么 <em>sSoleInstance == null</em> 条件对两个线程都成立,所以会创建同一个类的两个实例。这破坏了单例规则。</p>    <p>解决方法:</p>    <p>1.将getInstance()方法定义为synchronized:</p>    <p>我们将getInstance()方法定义为synchronized</p>    <pre>  <code class="language-java">public class SingletonClass {        private static SingletonClass sSoleInstance;        //private constructor.      private SingletonClass(){            //Prevent form the reflection api.          if (sSoleInstance != null){              throw new RuntimeException("Use getInstance() method to get the single instance of this class.");          }      }         public synchronized static SingletonClass getInstance(){          if (sSoleInstance == null){ //if there is no instance available... create new one              sSoleInstance = new SingletonClass();          }            return sSoleInstance;      }  }</code></pre>    <p>将 <em>getInstance()</em> 方法定义为synchronized,那么第二个线程就必须等待第一个线程的 <em>getInstance()</em> 方法运行完。这种方式能够达到线程安全的目的,但是使用这种方法有一些缺点:</p>    <ul>     <li>频繁的锁导致性能低下</li>     <li>一旦实例初始化完成,没有必要再进行同步操作</li>    </ul>    <p>2、双重检查锁方法:</p>    <p>如果我们使用双重检查锁方法来创建单例类则可以解决这个问题。在这种方法中,我们仅仅将实例为null条件下的代码块同步执行。所以只有在 <em>sSoleInstance</em> 为null的情况下同步代码块才会执行,这样一旦实例变量初始化成功就不会出现不必要的同步操作。</p>    <pre>  <code class="language-java">public class SingletonClass {        private static SingletonClass sSoleInstance;        //private constructor.      private SingletonClass(){            //Prevent form the reflection api.          if (sSoleInstance != null){              throw new RuntimeException("Use getInstance() method to get the single instance of this class.");          }      }        public static SingletonClass getInstance() {          //Double check locking pattern          if (sSoleInstance == null) { //Check for the first time                synchronized (SingletonClass.class) {   //Check for the second time.                //if there is no instance available... create new one                if (sSoleInstance == null) sSoleInstance = new SingletonClass();              }          }            return sSoleInstance;      }  }</code></pre>    <p>3、使用volatile</p>    <p>这个方法表面上看起来很完美,因为你只需要执行一次同步代码块,但是在你将 <em>sSoleInstance</em> 变量定义为 <em> volatile </em> 之前测试仍然会失败。</p>    <p>如果没有volatile修饰符,就可能会出现另一个线程可以访问到处于半初始化状态的_instance变量,但是使用了volatile类型的变量,它能保证:对 volatile 变量 <em>sSoleInstance</em> 的写操作,不允许和它之前的读写操作打乱顺序;对 volatile 变量 <em>sSoleInstance</em> 的读操作,不允许和它之后的读写乱序。</p>    <pre>  <code class="language-java">public class SingletonClass {            private static volatile SingletonClass sSoleInstance;            //private constructor.          private SingletonClass(){                //Prevent form the reflection api.              if (sSoleInstance != null){                  throw new RuntimeException("Use getInstance() method to get the single instance of this class.");              }          }            public static SingletonClass getInstance() {              //Double check locking pattern              if (sSoleInstance == null) { //Check for the first time                    synchronized (SingletonClass.class) {   //Check for the second time.                    //if there is no instance available... create new one                    if (sSoleInstance == null) sSoleInstance = new SingletonClass();                  }              }                return sSoleInstance;          }      }</code></pre>    <p>现在我们的单例类是线程安全的。保证单例线程安全是非常重要的,尤其是在Android应用这样的多线程应用环境。</p>    <h2>保证单例序列化安全:</h2>    <p>在分布式系统中,我们有时需要在单例类中实现 <em> Serializable </em> 接口。通过实现Serializable可以将它的一些状态存储在文件系统中以供后续使用。让我们来测试一下我们的单例类在序列化和反序列化以后是否能够只有一个实例?</p>    <pre>  <code class="language-java">public class SingletonTester {     public static void main(String[] args) {          try {              SingletonClass instance1 = SingletonClass.getInstance();              ObjectOutput out = null;                out = new ObjectOutputStream(new FileOutputStream("filename.ser"));              out.writeObject(instance1);              out.close();                //deserialize from file to object              ObjectInput in = new ObjectInputStream(new FileInputStream("filename.ser"));              SingletonClass instance2 = (SingletonClass) in.readObject();              in.close();                System.out.println("instance1 hashCode=" + instance1.hashCode());              System.out.println("instance2 hashCode=" + instance2.hashCode());            } catch (IOException | ClassNotFoundException e) {              e.printStackTrace();          }     }  }</code></pre>    <p><img src="https://simg.open-open.com/show/82efac568829c7bbcf476c280d33f073.png"></p>    <p>哈希值不相等</p>    <p>我们可以看到两个实例的哈希值并不相等。很显然还是违反了单例原则。上面描述的序列化单例问题是因为当我们需要反序列化一个单例时,会创建一个新的实例。</p>    <p>为了防止创建新的实例,我们必须提供 <em>readResolve()</em> 方法的实现。 <em>readResolve()</em> 取代了从数据流中读取对象。这样就能保证其他类通过序列化和反序列化来创建新的实例。</p>    <pre>  <code class="language-java">public class SingletonClass implements Serializable {        private static volatile SingletonClass sSoleInstance;        //private constructor.      private SingletonClass(){            //Prevent form the reflection api.          if (sSoleInstance != null){              throw new RuntimeException("Use getInstance() method to get the single instance of this class.");          }      }        public static SingletonClass getInstance() {          if (sSoleInstance == null) { //if there is no instance available... create new one              synchronized (SingletonClass.class) {                  if (sSoleInstance == null) sSoleInstance = new SingletonClass();              }          }            return sSoleInstance;      }        //Make singleton from serialize and deserialize operation.      protected SingletonClass readResolve() {          return getInstance();      }  }</code></pre>    <h2>结论:</h2>    <p>行文至此,我们已经创建了一个线程安全、反射安全的单例类。但是这个单例类仍然不是一个完美的单例。我们还可以通过克隆或者多个类加载来创建多个单例类的实例,从而破坏单例规则。但是在多数应用中,上面的单例实现能够完美的工作。</p>    <p> </p>    <p> </p>    <p>来自:http://www.jianshu.com/p/00b7fb6d5142</p>    <p> </p>