![](/img/trans.png)
[英]Singleton-like pattern allowing to create more than one instance in 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.