單例設(shè)計模式是最簡單也是最常用的設(shè)計模式;介紹單例模式幾種使用肿嘲;
1:餓漢式 靜態(tài) 第一次加載直接初始化
<pre>
public class Person_1 {
private static Person_1 person = new Person_1();
private Person_1() {
}
public static Person_1 getInstance() {
return person;
}
}
</pre>
2:懶漢式 使用時初始化(getInstance())
每次都需要同步
<pre>
public class Person_3 {
private static Person_3 person_3;
private Person_3() {
}
public static synchronized Person_3 getInstance() {
if (person_3 == null) {
person_3 = new Person_3();
}
return person_3;
}
}
</pre>
2)Double Check Lock(DCL) 實(shí)現(xiàn)單例
雙重判斷避免不必要的同步敲董;
<pre>
public class Person_2 {
private static Person_2 person_2;
private Person_2() {
}
public static Person_2 getInstance() {
if (person_2 == null) {
synchronized (Person_2.class) {
if (person_2 == null) {
person_2 = new Person_2();
}
}
}
return person_2;
}
}
</pre>-
靜態(tài)內(nèi)部類單例模式
第一次調(diào)用getInstance() 才會初始化
<pre>
public class Person_4 {
private Person_4() {
}
private static Person_4 person_4;
public static Person_4 getInstance() {
return SingleHolder.person_4;
}
private static class SingleHolder {
private static final Person_4 person_4 = new Person_4();
}
}
</pre>
4)枚舉
<pre>
public enum Person_5 {
INSTANCE;
@Override
public String toString() {
return super.toString();
}
}
</pre>
5)使用容器
<pre>
public class SingletonUtils {
private static HashMap<String, Object> singletonMap = new HashMap<>();private SingletonUtils() {
}
public static void setSingleton(String key, Object value) {
if (!singletonMap.containsKey(key)) {
singletonMap.put(key, value);
}
}public static Object getSingleton(String key) {
return singletonMap.get(key);
}
}
</pre>