Wednesday, 16 April 2014

HOW TO STOP CREATING OBJECTS BY SINGLETON

HOW TO STOP CREATING OBJECTS BY SINGLETON ?

STEP1:
Open Console Application
  
CODE:

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

namespace ConsoleApplication1
{

    Public sealed class SingletonClass
    {

        private static SingletonClass instance; //This will create a static instance of the class SingletonClass
        static int count = 0;


        private SingletonClass() //Private constructor
        { }

        public static SingletonClass Instance//First Public Property
        {
            get
            {
                if (instance == null)
                {
                    instance = new SingletonClass();
                }
                return instance;
            }
        }
        public static SingletonClass Instance1//Second Public Property
        {
            get
            {
                if (instance != null)
                {
                    instance = new SingletonClass();
                }
                return instance;
            }
        }
        public void DoWork()//One of the method in the Singleton class
        {
            Console.WriteLine("Object Created:{0}",++count);
        }


        static void Main(string[] args)
        {
            SingletonClass objMySingleton1 = SingletonClass.Instance; //First Created 5 objects is calling the class methods(DoWork()) but not the 6th and 7th
            SingletonClass objMySingleton2 = SingletonClass.Instance;
            SingletonClass objMySingleton3 = SingletonClass.Instance;
            SingletonClass objMySingleton4 = SingletonClass.Instance;
            SingletonClass objMySingleton5 = SingletonClass.Instance;
            if (SingletonClass.Instance == SingletonClass.Instance1)
            {
                SingletonClass objMySingleton6 = SingletonClass.Instance                                     SingletonClass objMySingleton7 = SingletonClass.Instance;      
            }
            objMySingleton1.DoWork();
            objMySingleton2.DoWork();
            objMySingleton3.DoWork();
            objMySingleton4.DoWork();
            objMySingleton5.DoWork();
          //objMySingleton6.DoWork();//No use of creating 6th, 7th and more objects because it will never call any methods in a class
          //objMySingleton7.DoWork();

            Console.ReadLine();
        }
    }
}



OUT PUT:
When we run the application only 5 objects only created














First Created 5 objects is calling the class methods(DoWork()) but not the 6th and 7th ,
No use of creating 6th, 7th and more objects because it will never call any methods in a class

No comments:

Post a Comment

Receive All Free Updates Via Facebook.