我需要一个单例类来实例化一些参数。我现在的做法是:
class SingletonExample
{
private SingletonExample mInstance;
//other members...
private SingletonExample()
{
}
public SingletonExample Instance
{
get
{
if (mInstance == null)
{
throw new Exception("Object not created");
}
return mInstance;
}
}
public void Create(string arg1, string arg2)
{
mInstance = new SingletonExample();
mInstance.Arg1 = arg1;
mInstance.ObjectCaller = new ObjectCaller(arg2);
//etc... basically, create object...
}
}
实例是“晚”创建的,这意味着我没有应用程序启动所需的所有参数。
一般来说,我不喜欢强制对方法调用进行排序,但我在这里看不到其他方法。 IoC 也不会解决它,因为我可以在容器中注册它,我也可以调用 Create()...
您认为这种情况还可以吗?你有别的想法吗?
编辑:我知道我写的例子不是线程安全的,线程安全不是问题的一部分
最佳答案
单例很丑但是...
public class Singleton
{
private static Singleton _instance = null;
private static Object _mutex = new Object();
private Singleton(object arg1, object arg2)
{
// whatever
}
public static Singleton GetInstance(object arg1, object arg2)
{
if (_instance == null)
{
lock (_mutex) // now I can claim some form of thread safety...
{
if (_instance == null)
{
_instance = new Singleton(arg1, arg2);
}
}
}
return _instance;
}
}
我认为 Skeet 几年前就写过一篇博客,它非常可靠。无需异常(exception),您无需记住哪些对象应该是单例并在出错时处理后果。
编辑:类型不相关使用你想要的,object
只是为了方便在这里使用。
关于c# - 带参数的单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4203634/