簡體   English   中英

一個以上單例C#實例

[英]more than one instance of singleton c#

是否有一種類似Singleton的模式的實現,該模式允許創建多個實例?

我的班級定義是:

public class Logger
{
    private Logger(string logPath)
    {
        this.logPath = logPath;
    }


    /// <summary>
    /// Creates singleton 
    /// </summary>
    /// <param name="logPath"></param>
    /// <returns></returns>
    public static Logger GetInstance(string logPath)
    {
        lock (instanceLock)
        {
            if (logger == null)
            {
                logger = new Logger(logPath);
            }
        }
        return logger;
    }

    public static Logger Instance()
    {
        return logger;
    }

    /// <summary>
    /// Destructor
    /// </summary>
    ~Logger()
    {
        try
        {
            this.Close();
        }
        catch (Exception)
        {
        }
    }
}

是否有一種類似Singleton的模式的實現,該模式允許創建多個實例。

如果要使用多個實例,則只允許直接構造該類,而不要使它成為單例。 就您而言,只需將構造函數公開,並刪除單例/實例邏輯。

就是說,這里有Multiton模式 ,它允許通過單個接口對多個實例進行鍵控訪問。

這是我使用的模式:

public class Logger
{
    private Logger(...) { ... }

    static Logger { /* initialize Errors, Warnings */ }

    public static Logger Errors { get; private set; }
    public static Logger Warnings { get; private set; }

    public void Write(string message) { ... }
}

如果要使用static Logger Lookup(string name)方法,也可以這樣做。

現在,在其他代碼中,您可以編寫Logger.Errors.Write("Some error"); Logger.Warnings.Write("Some warning");

額外的:您可以在Write方法中使用Environment.StackTrace來另外記錄調用Write方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM