【发布时间】:2012-02-29 01:50:59
【问题描述】:
我正在学习如何实现一些基本的设计模式。在学习单例模式时,我注意到网络上有两种常见的实现:
// Possibly from: http://www.yoda.arachsys.com/csharp/singleton.html
// I cannot remember exact source, sorry :(
public sealed class Singleton
{
// Static members are 'eagerly initialized', that is,
// immediately when class is loaded for the first time.
// .NET guarantees thread safety for static initialization
private static readonly Singleton instance = new Singleton();
// Private constructor prevents instantiation from other classes
private Singleton() { }
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
public static Singleton() { }
// Get the instance of the singleton
public static Singleton getInstance()
{
return instance;
}
}
和:
public class Singleton
{
// Static, VOLATILE variable to store single instance
private static volatile Singleton m_instance;
// Static synchronization root object, for locking
private static object m_syncRoot = new object();
// Property to retrieve the only instance of the Singleton
public static Singleton Instance
{
get
{
// Check that the instance is null
if (m_instance == null)
{
// Lock the object
lock (m_syncRoot)
{
// Check to make sure its null
if (m_instance == null)
{
m_instance = new Singleton();
}
}
}
// Return the non-null instance of Singleton
return m_instance;
}
}
}
- 在哪种情况下,您会选择急切初始化还是延迟初始化?
- 第一个示例中的注释是否正确地说初始化是线程安全的? (我知道它说是,但它是互联网......)
【问题讨论】:
-
这已被讨论并写到博客上。你真的必须把重点放在新的或非常具体的事情上。
-
如果你使用 .net 4,你可以选择使用 Lazy
(msdn.microsoft.com/fr-fr/library/dd642331.aspx) -
@HenkHolterman,我不这么认为。这个问题是问什么是好的实现,我问的是线程安全和示例用法:/
-
WRT 1..静态构造函数不允许访问修饰符。
标签: c# design-patterns