Singleton pattern generic code – example from C# 3.0 Design Patterns

Role

One way solution for achieving reusability of the Singleton Pattern

Implementation

using System;

namespace SingletonPatternGenericCode
{
    public class Singleton where T : class, new()
    {
        private Singleton()
        {
        }

        public static T UniqueInstance
        {
            get { return SingletonCreator.Instance; }
        }

        #region Nested type: SingletonCreator

        private class SingletonCreator
        {
            internal static readonly T Instance = new T();

            static SingletonCreator()
            {
            }
        }

        #endregion
    }

    internal class Test1
    {
    }

    internal class Test2
    {
    }

    public class Client
    {
        public static void Main()
        {
            Test1 t1A = Singleton.UniqueInstance;
            Test2 t2A = Singleton.UniqueInstance;
            Test1 t1B = Singleton.UniqueInstance;

            if (!Equals(t1A, t2A))
            {
                Console.WriteLine("t1a and t2a objects are different");
            }

            if (Equals(t1A, t1B))
            {
                Console.WriteLine("t1a and t2a objects are the same instance");
            }
        }
    }
}

Output:

t1a and t2a objects are different
t1a and t2a objects are the same instance

Bibliography

Advertisements

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 )

Google+ photo

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

Connecting to %s