確保某一個類只有一個實例,並且自行實例化並向整個系統提供這個實例git
public class Singleton {
private static final Singleton singleton = new Singleton();
//構造函數私有化
private Singleton() {
}
//公有的靜態函數,對外暴露獲取單例對象的接口
public static Singleton getInstance() {
return singleton;
}
}
複製代碼
public class Singleton {
private static Singleton singleton;
//構造函數私有化
private Singleton() {
}
//公有的靜態函數,對外暴露獲取單例對象的接口
public static synchronized Singleton getInstance() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}
複製代碼
以上的2種模式用的都很少,瞭解一下就好,下面介紹平時用得比較多的單例模式github
public class Singleton {
private volatile static Singleton singleton = null;
//構造函數私有化
private Singleton() {
}
//公有的靜態函數,對外暴露獲取單例對象的接口
public static Singleton getInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
複製代碼
public class Singleton {
private Singleton() {
}
public static Singleton getInstance() {
return SingletonHolder.sInstance;
}
//靜態內部類
private static class SingletonHolder {
private static final Singleton sInstance = new Singleton();
}
}
複製代碼
靜態內部類單例模式和DCL模式是推薦的單例實現模式數據庫
public enum Singleton {
INSTANCE;
}
複製代碼
源碼地址:https://github.com/snowdream1314/DesignPatternsExamples設計模式
歡迎關注個人微信公衆號,和我一塊兒學習一塊兒成長! 安全