單例模式的話,類圖上來看是最簡單的設計模式,就是一個類隻能有一個自己的執行個體。
單例模式通常來說我們就有Lazy loading的和不是Lazy loading的。《java與模式》裡面的關于這兩種的類圖,:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZwpmL5gDM1YTO3UzNykTMyADMxgTMwIzLcZDM0EDMy8CXvZmbp9CXt92YuUGZvNWatFWbuU2Zh1Wavw1LcpDc0RHaiojIsJye.jpg)
可以看到一個是現開始就執行個體話的,這樣的話不符合我們的lazy
loading,還有一種是在getinstance方法裡頭去new的,這樣的話會有線程安全的問題,我們提供了雙重檢查鎖。
下面看示意代碼︰
1. 靜态初始化:
2.雙重檢察鎖
3.靜态内部類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<code>package</code>
<code>com.javadesignpattern.Singleton;</code>
<code>public</code> <code>class</code> <code>SingletonStaticInnerClass {</code>
<code> </code>
<code> </code><code>private</code>
<code>SingletonStaticInnerClass(){</code>
<code> </code>
<code> </code><code>}</code>
<code> </code><code>static</code>
<code>class</code> <code>InnerClass{</code>
<code> </code><code>private</code>
<code>static</code> <code>SingletonStaticInnerClass instance =</code><code>new</code>
<code>SingletonStaticInnerClass();</code>
<code> </code><code>public</code>
<code>static</code> <code>SingletonStaticInnerClass getInstance(){</code>
<code> </code><code>return</code>
<code>InnerClass.instance;</code>
<code>}</code>
4. 枚舉
測試代碼:
枚舉的方式始effective java推薦的。序列化的時候能保證單例,而且比較簡單。當然别的方式的序列化可以用重寫 readreslove
來保證單例。
<code>//readResolve to prevent another instance of Singleton</code>
<code> </code><code>private</code> <code>Object readResolve(){</code>
<code> </code><code>return</code> <code>INSTANCE;</code>