![](/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.