首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

設計模式 C# 實作:單例與多例模式

     編輯:關於C#

單例模式

確保類別僅有一個實例,自行建立並提供全域存取點。三大特徵:唯一實例、自我建立、全域提供。

public class Singleton
{
    private static Singleton m_instance = null;
    private Singleton() { }
    public static Singleton GetInstance()
    {
        if (m_instance == null) m_instance = new Singleton();
        return m_instance;
    }
}

建構子私有防止繼承與外部實例化。

多例模式

單例自然推廣:允許有限數量實例,自我建立管理並對外提供。分有上限與無上限兩類。

有上限多例

上限寫死於類別內部邏輯。範例:最多兩個實例 instance1/instance2,依參數 whichOne 回傳對應實例。

public class Multiton
{
    private static Multiton instance1 = null, instance2 = null;
    private Multiton() { }
    public static Multiton GetInstance(int whichOne)
    {
        if (whichOne == 1) { if (instance1 == null) instance1 = new Multiton(); return instance1; }
        else { if (instance2 == null) instance2 = new Multiton(); return instance2; }
    }
}

無上限多例

實例數無上限,通常以集合 (如 List) 管理所有實例,雖為單例推廣但不一定能退化為單例。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved