Design Pattern

Singleton Design Pattern 

1.Single private constructor

2. A sealed class (can't not instantiate and not inherited)

3. A static variable to hold  & provide a single instance of class.

4. A public static method to get the reference of the single instance.

Syntax:

Public sealed class Singleton {

          private Singleton _instance = null;

          private Singleton (){

          }

          public static Singleton Instance {

                   get{

                         if(_instance ==null){

                               _instance = new Singleton();

                         }

                        return _instance;

                   }

          }

          public int x, y;

          public static int add(){

                return x+y;

          }

}

Client

Class ClassName {

    Singleton.Instance.x = 10;

    Singleton.Instance.y = 20;


    Singleton.Instance.add();   


}



        

No comments:

Post a Comment

Today Tasks