?有時候我們常常要在多處使用某一個類里的方法,但是若每一處都new一個實例實在是很耗系統資源的。這樣重復的定義式很浪費,這時編程中的“單例模式”就應運而生了。
單例模式的特點就是雖然在多處使用,但使用的卻是一個實例,請看下面代碼它是如何辦到的
?
using?System;???using?System.Collections.Generic;???using?System.Text;??????namespace?單例模式???{???????class?Program???????{???????????static?void?Main(string[]?args)???????????{???????????????Singleton?s1?=?Singleton.GetInstance();???????????????Singleton?s2?=?Singleton.GetInstance();??????????????????if?(s1?==?s2)???????????????{???????????????????Console.WriteLine("Objects?are?the?same?instance");???????????????}??????????????????Console.Read();???????????}???????}?????????????class?Singleton???????{???????????private?static?Singleton?instance;???????????private?static?readonly?object?syncRoot?=?new?object();????????????????????private?Singleton()???????????{???????????}??????????????public?static?Singleton?GetInstance()???????????{???????????????if?(instance?==?null)???????????????{??????????????????????lock?(syncRoot)???????????????????{??????????????????????????if?(instance?==?null)???????????????????????{???????????????????????????instance?=?new?Singleton();???????????????????????}???????????????????}???????????????}???????????????return?instance;???????????}??????????}??????}??? 運行的結果輸出:
?
Objects are the same instance
定義一個單例模式的類需要以下兩步:
第一步:將其無參構造函數定義成pirvate類型,使得外部調用時無法通過new定義一個無參的實例對象
?
private?Singleton()???{???}??? ?
第二步:定義一個public static類型的方法,這個方法返回的類型是這個類的類型。這個方法的作用就是實例化對象,若對象為空,則new一個實例,否則返回當前實例。
?
public?static?Singleton?GetInstance()???????????{???????????????if?(instance?==?null)???????????????{??????????????????????lock?(syncRoot)???????????????????{??????????????????????????if?(instance?==?null)???????????????????????{???????????????????????????instance?=?new?Singleton();???????????????????????}???????????????????}???????????????}???????????????return?instance;???????????}??? ?
轉載于:https://blog.51cto.com/cangkukuaimanle/674925
總結
以上是生活随笔為你收集整理的如何优化代码节约系统资源解决重复实例化对象的问题——神奇的单例模式(C#设计模式)...的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。