歡迎關注微信公衆號:FSA全棧行動 👋java
經過單例模式能夠保證系統中,應用該模式的類只有一個對象實例。安全
好處:微信
分類:markdown
class
一加載就建立)getInstance()
時再建立)實現步驟:多線程
/** * 單式模式:餓漢式 * * @author GitLqr */
public class SingletonHungry {
private static SingletonHungry instance = new SingletonHungry();
private SingletonHungry() {
}
public static SingletonHungry getInstanceHungry() {
return instance;
}
}
複製代碼
DCL,即雙重檢查鎖定 (Double-Checked-Locking)函數
synchronized
前第一次判空:避免沒必要要的加鎖同步,提升性能synchronized
後第二次判空:避免出現多線程安全問題volatile
修飾 instance:避免指令重排序問題/** * 單例模式:懶漢式 (DCL + volatile) * * @author GitLqr */
public class SingletonLazy {
private static volatile SingletonLazy instance;
private SingletonLazy() {
}
public static SingletonLazy getInstance() {
if (instance == null) {
synchronized (SingletonLazy.class) {
if (instance == null) {
instance = new SingletonLazy();
}
}
}
return instance;
}
}
複製代碼
Holder
靜態內部類:外部類加載時,並不會直接致使靜態內部類被加載,在調用 getInstance()
時纔會觸發該靜態內部類被加載,因此,能夠延時執行。Holder.instance
static 字段:同一個加載器下,一個類型只會初始化一次,故自然的線程安全。/** * 單例模式:懶漢式 (靜態內部類) * * @author GitLqr */
public class SingletonLazyClass {
private static class Holder {
private static SingletonLazyClass instance = new SingletonLazyClass();
}
public static SingletonLazyClass getInstance() {
return Holder.instance;
}
private SingletonLazyClass() {
}
}
複製代碼
注意:
靜態內部類
相比DCL
代碼簡潔不少,即有餓漢式的優點,又能夠作到延時初始化,看似很完美,但其有一個致命問題,即沒法傳參,因此,實際開發中,要根據實際狀況來選擇其中一種實現方式。oop
/** * 單例模式:懶漢式 (枚舉) * * @author GitLqr */
public enum SingletonEnum {
INSTANCE;
// 枚舉與普通類同樣,能夠擁有字段和方法
public void method() {
// TODO
}
}
複製代碼
注意:缺點跟
靜態內部類
方式同樣,外部沒法傳參。性能
public class SingletonLazy {
private static SingletonLazy instance;
private SingletonLazy() {
}
public static SingletonLazy getInstance() {
if (instance == null) {
instance = new SingletonLazy();
}
return instance;
}
}
複製代碼
public class SingletonLazy {
private static SingletonLazy instance;
private SingletonLazy() {
}
public static synchronized SingletonLazy getInstance() {
if (instance == null) {
instance = new SingletonLazy();
}
return instance;
}
}
複製代碼
public class SingletonLazy {
private static SingletonLazy instance;
private SingletonLazy() {
}
public static SingletonLazy getInstance() {
if (instance == null) {
synchronized (SingletonLazy.class) {
if (instance == null) {
instance = new SingletonLazy();
}
}
}
return instance;
}
}
複製代碼
public class SingletonLazy {
private static volatile SingletonLazy instance;
private SingletonLazy() {
}
public static SingletonLazy getInstance() {
if (instance == null) {
synchronized (SingletonLazy.class) {
if (instance == null) {
instance = new SingletonLazy();
}
}
}
return instance;
}
}
複製代碼
若是文章對您有所幫助, 請不吝點擊關注一下個人微信公衆號:FSA全棧行動, 這將是對我最大的激勵. 公衆號不只有Android技術, 還有iOS, Python等文章, 可能有你想要了解的技能知識點哦~spa