Singleton Pattern

If you don’t want to use static methods for whatever reason, you can still gain the benefits of static methods by using the singleton pattern. The resultant behavior is that the entire object acts like it’s static.

using System.Diagnostics;

namespace Company.Product
{
    internal class Singleton
    {
        // We make the constructor private so the class
        // can't be externally instantiated.
        private Singleton(){}

        static private Singleton _localStaticInstance;

        // We add a static method that will return
        // the instance object that's stored internally.
        static public Singleton Instance
        {
            get
            {
                if (_localStaticInstance == null)
                {
                    _localStaticInstance = new Singleton();
                }
                return _localStaticInstance;
            }
        }

        public string GetWorld()
        {
            return "Hello!";
        }
    }

    internal class Test
    {
        public void Exercise()
        {
            // The static instance method actually returns an instantiated object.
            // It's instantiated internally and every call to the static method returns
            // the same instance every time.  Caching is fun!
            Debug.Print(Singleton.Instance.GetWorld());

            // Or if you don't want to type 'Singleton.Instance' every time,
            // you can store a reference locally for less typing.
            var singleton = Singleton.Instance;
            Debug.Print(singleton.GetWorld());
            Debug.Print(singleton.GetWorld());
            Debug.Print(singleton.GetWorld());
        }
    }
}
Advertisements