Code Snippet: Singleton

By: Nicklas Møller Jepsen

I’ve written some code snippets which makes the daily job as a developer more convenient. These snippets are for use with Visual Studio.

If you want to have a look at how these snippets are added to Visual Studio see how to add a snippet here.

This post is about the Singleton pattern and the snippet I use to quickly implement this pattern in a class.

The Singleton pattern is a pattern that make sure that only one instance of an object exists. Al thou there might be pros and cons for using the pattern, but for instance settings classes and controllers it probably is best that these are always single instances.

The snippet looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
			<Description>Implement the Singleton pattern here.</Description>
			<Author>Nicklas Møller Jepsen</Author>
				<ToolTip>The name of the property to get a Singleton instance</ToolTip>
			<Literal default="true" Editable="false">
                    <ToolTip>Class name</ToolTip>

		<Code Language="csharp" Kind="method head"><![CDATA[private static $classname$ _instance;
		private $classname$() {}

		public static $classname$ $instancepropname$
				if (_instance == null)
					_instance = new $classname$();
				return _instance;

Remember to use the Source, Luke – so don’t go abusing the above. Singletons are good, but only when they are needed. Or something like that :)