Wednesday, 13 January 2016

C# Design patterns(single tone)

(1)Single tone pattern
================================================================

=>Single tone pattern is used to maintain single instance in thought application.It will check already instance is created or not if instance is created it will return existing object other wise it will create new instance.

=>Single tone pattern the main class it will contain private constructor.So it will not allow out side to create an instance for this class.if we try to create an instance it will through an compile time error.

Ex.

(a)Single tone class
=================
public class Singleton
    {
        private static Singleton instance = null;
        private string Name { get; set; }
        private string IP { get; set; }
        private Singleton()
        {
            Name = "Server1";
            IP = "192.168.1.23";
        }
        public static Singleton Instance
        {
            get
            {
                    if (Singleton.instance == null)
                        Singleton.instance = new Singleton();

                    return Singleton.instance;
            }
        }

        public void Show()
        {
            Console.WriteLine("Server Information is : Name={0} & IP={1}", IP, Name);
        }

    }
(b)Implementation class
===================
class Program
    {
        static void Main(string[] args)
        {

            Singleton.Instance.Show();
            Singleton.Instance.Show();
            Console.Read();
        }
    }



No comments:

Post a Comment