[英]more than one instance of singleton c#
Is there a realisation of a Singleton-like pattern which allows to create more than one instance? 是否有一种类似Singleton的模式的实现,该模式允许创建多个实例?
My class definition is: 我的班级定义是:
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)
{
}
}
}
Is there a realisation of a Singleton-like pattern which allows to create more than one instance.
是否有一种类似Singleton的模式的实现,该模式允许创建多个实例。
If you want multiple instances, just allow the class to be constructed directly, and don't make it a singleton. 如果要使用多个实例,则只允许直接构造该类,而不要使它成为单例。 In your case, just make the constructor public, and remove the singleton/instance logic.
就您而言,只需将构造函数公开,并删除单例/实例逻辑。
That being said, there is the Multiton pattern , which allows keyed access to multiple instances via a single interface. 就是说,这里有Multiton模式 ,它允许通过单个接口对多个实例进行键控访问。
This is the pattern I use: 这是我使用的模式:
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) { ... }
}
If you want to have a static Logger Lookup(string name)
method, you can do that too. 如果要使用
static Logger Lookup(string name)
方法,也可以这样做。
Now in other code you can write Logger.Errors.Write("Some error");
现在,在其他代码中,您可以编写
Logger.Errors.Write("Some error");
or Logger.Warnings.Write("Some warning");
或
Logger.Warnings.Write("Some warning");
. 。
Bonus: you can use Environment.StackTrace
inside of your Write
method to additionally log what method you called Write
from. 额外的:您可以在
Write
方法中使用Environment.StackTrace
来另外记录调用Write
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.