M
Mountain Bikn' Guy
Is the second version shown below better? I couldn't locate enough info
about [MethodImpl(MethodImplOptions.Synchronized)] in order to tell.
1.. My commonly used singleton pattern implementation looks like this (it
was inspired by Eric Gunnerson's book):
private static volatile MyClass singleton = null;
private static object sync = new object();//for static lock
public static MyClass Instance
{
get
{
if (singleton == null)
{
lock (sync)
{
if (singleton == null)
{
singleton = new MyClass ();
}
}
}
return singleton;
}
}//Instance
2. An alternate implementation inspired by 'Design Patterns Explained: A New
Perspective on Object-Oriented Design' by by Alan Shalloway, James R. Trott.
public static MyClass Instance
{
get
{
if (s_Instance == null)
{
DoSynchronizedExistenceCheck();
}
return s_Instance;
}
}
[MethodImpl(MethodImplOptions.Synchronized)]
private static void DoSynchronizedExistenceCheck()
{
if (s_Instance == null)
{
s_Instance = new MyClass();
}
}
about [MethodImpl(MethodImplOptions.Synchronized)] in order to tell.
1.. My commonly used singleton pattern implementation looks like this (it
was inspired by Eric Gunnerson's book):
private static volatile MyClass singleton = null;
private static object sync = new object();//for static lock
public static MyClass Instance
{
get
{
if (singleton == null)
{
lock (sync)
{
if (singleton == null)
{
singleton = new MyClass ();
}
}
}
return singleton;
}
}//Instance
2. An alternate implementation inspired by 'Design Patterns Explained: A New
Perspective on Object-Oriented Design' by by Alan Shalloway, James R. Trott.
public static MyClass Instance
{
get
{
if (s_Instance == null)
{
DoSynchronizedExistenceCheck();
}
return s_Instance;
}
}
[MethodImpl(MethodImplOptions.Synchronized)]
private static void DoSynchronizedExistenceCheck()
{
if (s_Instance == null)
{
s_Instance = new MyClass();
}
}