單例模式
- 簡單理解為,有一個類,只能有一個實體化物件,這就是單例模式,
- 節約記憶體,防止造成記憶體浪費
話不多說 直接上代碼.
/**
* 不處于執行緒的方式考慮!!!單例模式
*
* Created by zhaiyachao on 2020/10/30.
*/
public class SingletonTest {
private Boolean st;
private Boolean en;
public static SingletonTest instance=null;
public SingletonTest() {
// 隨著構造加載賦值
this.st = true;
this.en = false;
}
public static SingletonTest getInstance(){
if (instance==null){
instance=new SingletonTest();
}
return instance;
}
}
- 思考:
- 按照多執行緒的角度去考慮…! 會產生執行緒不安全… Why ?
- 假設: 兩個執行緒,同時呼叫getInstance方法. {執行緒1.與執行緒2.執行到 if (instance==null) }
都會重復執行, 起初 instance 為null- 解決的方案有三種
- 雙重加鎖
- 同步鎖
- 簡單暴力.直接創建物件
- 請看一下代碼
- 第一種方案
最為簡單粗暴的一個
public class SingletonTest {
private Boolean st;
private Boolean en;
// 一開始就創建了物件
public static SingletonTest instance=new SingletonTest();
public SingletonTest() {
this.st = true;
this.en = false;
}
public static synchronized SingletonTest getInstance(){
if (instance==null){
instance=new SingletonTest();
}
return instance;
}
}
- 同步鎖方式實作
// 多執行緒的情況下, 呼叫多次, 效率會慢. 消耗資源
public static synchronized SingletonTest getInstance(){
if (instance==null){
instance=new SingletonTest();
}
return instance;
}
- 雙重加鎖方式實作
public class SingletonTest {
private Boolean st;
private Boolean en;
// 交給編譯器
public volatile static SingletonTest instance=null;
public SingletonTest() {
this.st = true;
this.en = false;
}
public static synchronized SingletonTest getInstance(){
// 雙重檢索的方式
if (instance==null) {
synchronized (SingletonTest.class) {
if (instance == null) {
instance = new SingletonTest();
}
}
}
return instance;
}
}
其他設計模式. 待續…!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/198658.html
標籤:其他
