C# Design Pattern–Singleton

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Singleton
{
    public class MainEntry
    {
        static void Main()
        {
            // Create Instances of Singleton class
            ConnectionPool p1 = ConnectionPool.Instance;
            ConnectionPool p2 = ConnectionPool.Instance;

            // Prove Instance are singleton, use Equals for Reference types
            if (p1.Equals(p2))
                Console.WriteLine("Both Instances are equal");

            // Sample operation on singleton instance
            for (int i = 0; i < 20; i++)
            {
                Console.WriteLine(p1.GetConnection().Connection);
            }

            // Hold the console without disappearing
            Console.ReadLine();
        }
    }

    // Sealed class makes sure it is not inherited. If inheritance required, go to Abstract Pattern.
    public sealed class ConnectionPool
    {
        //public static property used to expose Singleton instance.
        public static ConnectionPool Instance
        {
            get
            {
                return InternalSingleton._pool;
            }
        }

        private List<SqlConnectionString> _connections;
        private Random _r = new Random();

        // private constructor
        private ConnectionPool()
        {
            _connections = new List<SqlConnectionString>();
            _connections.Add(new SqlConnectionString() { Connection = "SqlConnection1" });
            _connections.Add(new SqlConnectionString() { Connection = "SqlConnection2" });
            _connections.Add(new SqlConnectionString() { Connection = "SqlConnection3" });
            _connections.Add(new SqlConnectionString() { Connection = "SqlConnection4" });
        }

        // Sample method to perform operations
        public SqlConnectionString GetConnection()
        {
            return _connections[_r.Next(_connections.Count)];
        }

        // Nested class is required to have fully lazy implementation of Singleton pattern.
        class InternalSingleton
        {
            // Static constructor makes sure instance has been initiated.
            static InternalSingleton()
            {
            }

            internal static readonly ConnectionPool _pool = new ConnectionPool();
        }
    }

    // Class to be acted for skeleton operations.
    public class SqlConnectionString
    {
        public string Connection { get; set; }
    }
}

 

Output -

Singleton

You may also like...