單例模式的定義:保證一個類僅有一個實例,並提供一個訪問它的全局訪問點! 1、懶漢 2、餓漢 3、雙重校驗鎖 4、枚舉 5、靜態內部類 本文永久更新地址: "https://github.com/nnngu/LearningNotes/blob/master/Java%20Basis/019%20%E ...
單例模式的定義:保證一個類僅有一個實例,並提供一個訪問它的全局訪問點!
1、懶漢
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
2、餓漢
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton (){}
public static Singleton getInstance() {
return instance;
}
}
3、雙重校驗鎖
public class Singleton {
private volatile static Singleton singleton;
private Singleton (){}
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
4、枚舉
public enum Singleton {
INSTANCE;
public void whateverMethod() {
}
}
5、靜態內部類
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton (){}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}