h1

C# Singleton for Facade Pattern

August 7, 2011

While researching the facade pattern that can be implemented in similar way to HttpContext (in ASP.net), I came to a MSDN article that talks about implementing the singleton patternĀ in C#. It is fairly straight forward and works extremely well for what I needed for the project.

Here is the context class, which exposees the CMSManager (a factory class). The context manages the instantiation and destruction of the facade:

public sealed partial class CMSContext
{
	/// <summary>
	/// clutch object is used to prevent multiple access during the initialization
	/// </summary>
	private static object clutch = new object();
	/// <summary>
	/// actual instance of the CMSContext object
	/// </summary>
	private static volatile CMSContext uniqueInstance;

	/// <summary>
	/// instance of the CMSManager
	/// </summary>
	private CMSManager _cmsFacade = null;

	/// <summary>
	/// Gets the CMS facade.
	/// </summary>
	public CMSManager CMSFacade
	{
		get
		{
			return _cmsFacade;
		}
	}

	/// <summary>
	/// Prevents a default instance of the <see cref="CMSContext"/> class from being created.
	/// </summary>
	private CMSContext()
	{
		_cmsFacade = new CMSManager();
	}

	/// <summary>
	/// Gets the instance.
	/// </summary>
	public static CMSContext Instance
	{
		get
		{
			if (uniqueInstance == null)
			{
				lock (clutch)
				{
					if (uniqueInstance == null)
						uniqueInstance = new CMSContext();
				}
			}
			return uniqueInstance;
		}
	}

	/// <summary>
	/// Releases unmanaged resources and performs other cleanup operations before the
	/// <see cref="CMSContext"/> is reclaimed by garbage collection.
	/// </summary>
	~CMSContext()
	{
		if (_cmsFacade != null) _cmsFacade.Dispose();
	}

}


This context class simplifies the way my client application accesses the CMS subsystem. It only requires two lines of code to access the factory class.

CMSContext cms = CMSContext.Instance;

ContentFile f = new ContentFile();
f.FileName = "Test.txt";
f.FileSize = 10;
f.LastModified = DateTime.Now;

cms.CMSFacade.SaveContent(f);

One important note to achieve this simplicity, both context class and factory class should be autonomous; if there is any external dependency, it can make the client code messy.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.