1. 程式人生 > >建立型設計模式之單例設計模式

建立型設計模式之單例設計模式

概念解釋:確保一個類只有一個例項,並提供一個全域性訪問點。

應用場景
1.多執行緒的執行緒池,方便控制及節約資源。
2.windows電腦的工作管理員就是,不信你試試。
3.windows電腦的回收站也是。
4.資料庫的連線池設計,一般也採用單例設計模式,資料庫連線是一種資料庫資源。在資料庫軟體系統中
使用資料庫連線池,可以節省開啟或關閉資料庫連線引起的效率損耗,用單例模式維護,就可以大大降低這種損耗。
5.應用程式的日誌應用,由於共享的日誌檔案一直處於開啟狀態,只能有一個例項去操作,否則內容不好追加。

為了便於理解程式碼示例如下:

using System;
using System.Collections.Generic;
using System.Linq; using System.Text; using System.Threading.Tasks; namespace SingleTon { public sealed class Singleton { static Singleton instance = null; private static readonly object padlock = new object(); private Singleton() { } public static
Singleton Instance { get { if (instance == null) { lock(padlock)//如果考慮多執行緒,加鎖是很好的解決方案 { if(instance == null) { instance = new Singleton(); } } }
return instance; } } } }