Friday, October 19, 2007

Creational Design Pattern

Singleton

The singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object. To make sure that the object cannot be instantiated any other way, the constructor is made either private or protected. Note the distinction between a simple static instance of a class and a singleton: although a singleton can be implemented as a static instance, it can also be lazily constructed, requiring no memory or resources until needed. Another notable difference is that static member classes cannot implement an interface, unless that interface is simply a marker. So if the class has to realize a contract expressed by an interface, you really have to make it a singleton.

The singleton pattern must be carefully constructed in multi-threaded applications. If two threads are to execute the creation method at the same time when a singleton does not yet exist, they both must check for an instance of the singleton and then only one should create the new one. If the programming language has concurrent processing capabilities the method should be constructed to execute as a mutually exclusive operation.

The classic solution to this problem is to use mutual exclusion on the class that indicates that the object is being instantiated.



C# (using generics)

This example is thread-safe with lazy initialization.

///
/// Generic class implements singleton pattern.
///

///
/// Reference type.
///

public class Singleton where T : class, new()
{
///
/// Get the Singleton Instance.
///

public static T Instance
{
get { return SingletonCreator._instance ; }
}

class SingletonCreator
{
static SingletonCreator() { }

internal static readonly T _instance = new T();
}
}

C# (using generics and reflection)

This example is thread-safe with lazy initialization. In addition, this example is suit for classes which have private constructor.

///
/// Generic class implements singleton pattern.
///

///
[CLSCompliant(true)]
public static class Singleton where T : class, new()
{
private static T _instance;

static Singleton() {
Type type = typeof(T);
BindingFlags searchPattern = BindingFlags.NonPublic |
BindingFlags.Public |
BindingFlags.Instance;
ConstructorInfo constructor = type.GetConstructor(searchPattern,
null,
Type.EmptyTypes,
null);

_instance = (T)constructor.Invoke(new object[0]);
}

///
/// Get the singleton instance of the type.
///

public static T Instance {
get { return _instance; }
}
}

public class Session
{
private Session() {
}
}

public class Program
{
private static void Main() {
Session instanceA = Singleton.Instance;
Session instanceB = Singleton.Instance;

// Are they the same?
Console.WriteLine(instanceA == instanceB); // true
}
}

Source :

No comments: