單例模式:乙個類在記憶體中只有乙個物件(例項),並且提供乙個可以全域性訪問或者獲取這個物件的方法。
這兩天學的,寫了個小例子,問了同事一些關於執行緒的問題,還有從網上查了一些資料。還犯了一些低階的錯誤。
vs2017控制台輸出文字亂碼,從網上找了一些方法不管用,最後發現是自己新建專案選錯模板了,選擇了.net core的模板,所以才會輸出亂碼,大家一定要吸取教訓。
直接上**
演示類,person.cs
public class person
/// 例項化乙個私有靜態變數,儲存類本身的例項
private static person _person = null;
/// 建構函式
private person()
console.writeline("構造了乙個",gettype().name);
public static person getinstance()
", object.referenceequals(person1, person2));}
輸出結果:
只輸出了一次,兩個物件引用相等。說明單例模式沒問題。
高階:public class person
/// 例項化乙個私有靜態變數,儲存類本身的例項
private static person _person = null;
/// 建構函式
private person()
console.writeline("構造了乙個",gettype().name);
} public static person getinstance()
);var thread2 = new thread(() => );
var thread3 = new thread(() => );
thread1.start();
thread2.start();
thread3.start();
thread.sleep(1000);//等待子執行緒完成
console.writeline("person1 == person2:", object.referenceequals(person1, person2));
輸出結果:
輸出了多次,引用也不相等。說明多次例項化這個類,單例模式寫的不完全正確,那讓我們加上執行緒安全驗證。
繼續高階:
public class person
/// 例項化乙個私有靜態變數,儲存類本身的例項
private static person _person = null;
/// 作為鎖的物件,使用私有的、靜態的並且是唯讀的物件
private static readonly object _obj = new object();
/// 建構函式
private person()
console.writeline("構造了乙個",gettype().name);
/// 獲取類唯一的例項物件
public static person getinstance()
if (_person == null)//先判斷是否為空
return _person;
客戶端呼叫**:
//使用鎖,鎖住的物件:使用私有的、靜態的並且是唯讀的物件
person person1 = null;
person person2 = null;
person person3 = null;
//多執行緒下可以輸出多次
var thread1 = new thread(() => );
var thread2 = new thread(() => );
var thread3 = new thread(() => );
thread1.start();
thread2.start();
thread3.start();
thread.sleep(1000);//等待子執行緒完成
console.writeline("person1 == person2:", object.referenceequals(person1, person2));
輸出結果:
輸出一次,引用相等,說明單例模式成功,執行緒安全已經加上。
高階2可以使用靜態建構函式作為單例模式:
public class person
/// 例項化乙個私有靜態變數,儲存類本身的例項
private static person _person = null;
/// 建構函式
private person()
console.writeline("構造了乙個",gettype().name);
/// 靜態建構函式,只執行一次
static person()
_person = new person();
/// 獲取類的例項
public static person getinstance()
);var thread2 = new thread(() => );
var thread3 = new thread(() => );
thread1.start();
thread2.start();
thread3.start();
thread.sleep(1000);//等待子執行緒完成
console.writeline("person1 == person2:", object.referenceequals(person1, person2));
c 多執行緒單例模式 執行緒安全C 單例模式
我對此處記錄的單例模式有一些疑問 http us library ff650316.aspx 以下 摘自該文章 using system public sealed class singleton private static volatile singleton instance private ...
c 多執行緒單例模式 C 單例模式實現
單例模式,可以說設計模式中最常應用的一種模式了。但是如果沒有學過設計模式的人,可能不會想到要去應用單例模式,面對單例模式適用的情況,可能會優先考慮使用全域性或者靜態變數的方式,這樣比較簡單,也是沒學過設計模式的人所能想到的最簡單的方式了。一般情況下,我們建立的一些類是屬於工具性質的,基本不用儲存太多...
C 設計模式之單例模式
在遊戲開發過程中,我們時常會遇到單例模式的運用場景。比如你遊戲當中的最終boss,你希望你的boss只能有乙個,所以這裡你就可以用單例模式 那麼什麼是單例模式呢?看下面的 分析。include include using namespace std class singleton public st...