Thursday, February 9, 2012

Real world example of singleton design pattern


using System;
using System.Collections.Generic;

namespace SingletonExample
{
    /*
    *This real-world code demonstrates the Singleton pattern as a LoadBalancing object.
    * Only a single instance (the singleton) of the class can be created because servers may
    * dynamically come on-line or off-line and every request must go throught the one object that
    * has knowledge about the state of the (web) farm.
    */
    class Program
    {
        static void Main(string[] args)
        {
            LoadBalancer lb1 = LoadBalancer.GetLoadBalancer();
            LoadBalancer lb2 = LoadBalancer.GetLoadBalancer();
            LoadBalancer lb3 = LoadBalancer.GetLoadBalancer();

            if (lb1 == lb2 && lb1 == lb3 && lb2 == lb3 && lb1 == lb2)
            {
                Console.WriteLine("Same instance of the class");
            }

            LoadBalancer balancer = LoadBalancer.GetLoadBalancer();
            for (int i = 0; i < 15; i++)
            {
                string server = balancer.server();
                Console.WriteLine("Dispatch Request to: " + server);
            }

            Console.Read();
        }
     
    }

    class LoadBalancer
    {
        private static LoadBalancer _loadbalencer;
        private List<String> _servers = new List<String>();
        private Random _random = new Random();

        private static object synlock = new object();


        protected LoadBalancer()
        {
            _servers.Add("Server 1");
            _servers.Add("Server 2");
            _servers.Add("Server 3");
            _servers.Add("Server 4");
            _servers.Add("Server 5");
        }

        public static LoadBalancer GetLoadBalancer()
        {
            if (_loadbalencer == null)
            {
                lock (synlock)
                {
                    if (_loadbalencer == null)
                    {
                        _loadbalencer = new LoadBalancer();
                    }
                }
            }
            return _loadbalencer;
        }

        public String server()
        {
            int rand = _random.Next(_servers.Count);
            return _servers[rand].ToString();
        }
    }
}

Output:


Same instance of the class
Dispatch Request to: Server 5
Dispatch Request to: Server 3
Dispatch Request to: Server 2
Dispatch Request to: Server 2
Dispatch Request to: Server 4
Dispatch Request to: Server 2
Dispatch Request to: Server 1
Dispatch Request to: Server 1
Dispatch Request to: Server 3
Dispatch Request to: Server 2
Dispatch Request to: Server 5
Dispatch Request to: Server 2
Dispatch Request to: Server 3
Dispatch Request to: Server 5
Dispatch Request to: Server 3



Post a Comment