· code-snippet c-sharp Design patterns Singleton Snippet

'Code Snippet – Singleton'

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">
        <Header>
            <Title>Singleton</Title>
            <Shortcut>sglt</Shortcut>
            <Description>Implement the Singleton pattern here.</Description>
            <Author>Nicklas Møller Jepsen</Author>
            <SnippetTypes>
                <SnippetType>Expansion</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
        <Declarations>
            <Literal>
                <ID>instancepropname</ID>
                <ToolTip>The name of the property to get a Singleton instance</ToolTip>
                <Default>Instance</Default>
            </Literal>
            <Literal default="true" Editable="false">
                    <ID>classname</ID>
                    <ToolTip>Class name</ToolTip>
                    <Function>ClassName()</Function>
                    <Default>ClassNamePlaceholder</Default>
                </Literal>

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

        public static $classname$ $instancepropname$
        {
            get
            {
                if (_instance == null)
                    _instance = new $classname$();
                return _instance;
            }
        }
        $end$
        ]]>
        </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

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 :)

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket