我有以下C#单例模式,有什么方法可以改进它吗?
public class Singleton<T> where T : class, new()
{
private static object _syncobj = new object();
private static volatile T _instance = null;
public static T Instance
{
get
{
if (_instance == null)
{
lock (_syncobj)
{
if (_instance == null)
{
_instance = new T();
}
}
}
return _instance;
}
}
public Singleton()
{ }
}
Run Code Online (Sandbox Code Playgroud)
首选用法示例:
class Foo : Singleton<Foo>
{
}
Run Code Online (Sandbox Code Playgroud)
相关:
这不是一个更简单,更安全(因此更好)的方法来实现单例而不是双重检查锁定mambo-jambo?这种方法有什么缺点吗?
public class Singleton
{
private static Singleton _instance;
private Singleton() { Console.WriteLine("Instance created"); }
public static Singleton Instance
{
get
{
if (_instance == null)
{
Interlocked.CompareExchange(ref _instance, new Singleton(), null);
}
return _instance;
}
}
public void DoStuff() { }
}
Run Code Online (Sandbox Code Playgroud)
编辑:线程安全测试失败,谁能解释为什么?为什么Interlocked.CompareExchange不是真正的原子?
public class Program
{
static void Main(string[] args)
{
Parallel.For(0, 1000000, delegate(int i) { Singleton.Instance.DoStuff(); });
}
}
Result (4 cores, 4 logical processors)
Instance created
Instance created
Instance created
Instance created
Instance created
Run Code Online (Sandbox Code Playgroud) 我有另一个面试问题.我觉得这很愚蠢,但也许有些东西我不知道了.问题是这是哪个GoF模式(答案:单身),如果有任何问题,我如何解决它们.
我没有看到任何问题.我提到这从未被释放过,我希望从这种模式中获得.这就是我所说的.我错过了什么吗?
public class Class1
{
private static Class1 oInstance = null;
private Class1() { }
public static Class1 GetInstance()
{
if (oInstance == null)
{
oInstance = new Class1();
}
return oInstance ;
}
}
Run Code Online (Sandbox Code Playgroud) 我实现了像这样的Singleton模式:
public sealed class MyClass {
...
public static MyClass Instance {
get { return SingletonHolder.instance; }
}
...
static class SingletonHolder {
public static MyClass instance = new MyClass ();
}
}
Run Code Online (Sandbox Code Playgroud)
从谷歌搜索C#Singleton实现,似乎这不是在C#中做事的常用方法.我发现了一个类似的实现,但SingletonHolder类不是静态的,并且包含一个显式(空)静态构造函数.
这是实现Singleton模式的有效,懒惰,线程安全的方法吗?还是有什么我想念的?
我有一个程序集,其目的是基本日志记录。
我有其他程序集引用了这个程序集。
有没有办法在引用程序集之间共享对象实例?那么,对于一个日志活动,只使用日志类的一个实例?
例如,如果 Logger 程序集/命名空间中的方法被调用AddInfo()。当程序集 A 有一个类需要记录它使用的信息时loggerInstance1.AddInfo()……当程序集 B 需要做同样的事情时……它重复使用相同的loggerInstance1.AddInfo()……而不是loggerInstance2.AddInfo()