Singleton design pattern code example

Ensure a class has only one instance and provide a global point of access to it.





Example 1:

using System;

namespace DoFactory.GangOfFour.Singleton.Structural
{

// MainApp test application

class MainApp
{

static void Main()
{
// Constructor is protected -- cannot use new
Singleton s1 = Singleton.Instance();
Singleton s2 = Singleton.Instance();

if (s1 == s2)
{
Console.WriteLine("Objects are the same instance");
}

// Wait for user
Console.Read();
}
}

// "Singleton"

class Singleton
{
private static Singleton instance;

// Note: Constructor is 'protected'
protected Singleton()
{
}

public static Singleton Instance()
{
// Use 'Lazy initialization'
if (instance == null)
{
instance = new Singleton();
}

return instance;
}
}
}



Example2:

///
/// Class implements singleton pattern.
///

public class Singleton
{
// Private constructor to avoid other instantiation
// This must be present otherwise the compiler provide
// a default public constructor
private Singleton()
{
}

///
/// Return an instance of
///

public static Singleton Instance
{
get
{
/// An instance of Singleton wont be created until the very first
/// call to the sealed class. This a CLR optimization that ensure that
/// we have properly lazy-loading singleton.
return SingletonCreator.CreatorInstance;
}
}

///
/// Sealed class to avoid any heritage from this helper class
///

private sealed class SingletonCreator
{
// Retrieve a single instance of a Singleton
private static readonly Singleton _instance = new Singleton();

///
/// Return an instance of the class
///

public static Singleton CreatorInstance
{
get { return _instance; }
}
}
}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: