Program.cs 2.34 KB
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

//Ensure a class has only one instance and provide a global point of access to it.

namespace Singleton
{
    /// <summary>

    /// MainApp startup class for Structural

    /// Singleton Design Pattern.

    /// </summary>

    class MainApp
    {
        /// <summary>

        /// Entry point into console application.

        /// </summary>

        static void Main()
        {
            // Constructor is protected -- cannot use new

            Singleton s1 = Singleton.Instance();
            Singleton s2 = Singleton.Instance();

            // Test for same instance

            if (s1 == s2)
            {
                Console.WriteLine("Objects are the same instance");
            }

            // Wait for user

            Console.ReadKey();
        }
    }

    /// <summary>

    /// The 'Singleton' class

    /// </summary>

    sealed class Singleton
    {
        private static Singleton _instance;
        private static readonly object padlock = new object();

        // Constructor is 'private'

        private Singleton()
        {
        }

        public static Singleton Instance()
        {
            // Uses lazy initialization.

            // Note: this is thread safe.
            lock (padlock)
            {
                if (_instance == null)
                {
                    _instance = new Singleton();
                }
            }
            return _instance;
        }
    }


    public sealed class SingletonWithOutLock
    {
        private static readonly SingletonWithOutLock instance = new SingletonWithOutLock();

        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static SingletonWithOutLock()
        {
        }

        private SingletonWithOutLock()
        {
        }

        public static SingletonWithOutLock Instance
        {
            get
            {
                return instance;
            }
        }
    }

    public sealed class Singleton4Framework
    {
        private static readonly Lazy<Singleton4Framework> lazy =
            new Lazy<Singleton4Framework>(() => new Singleton4Framework());

        public static Singleton4Framework Instance { get { return lazy.Value; } }

        private Singleton4Framework()
        {
        }
    }
}