sabato 27 aprile 2019

Design Patterns : Singleton

Singleton is very easy design pattern, it is used to instantiate an object only 1 time in the application.
It's like a static member.
You have to create a class and add a private member of the same class (the instance of the class), then you have to set private the constructor and add a method to get the instance that creates a new instance if not already created, otherwise it returns the private member.

static class Singleton
{
       private static Singleton instance;
   
       pubic static GetInstance()
       {
              if (instance == null)
                    instance = new Singleton();
              return instance;
       }
}

Usage:

var mySingleton1 = Singleton.GetInstance();
var mySingleton2 = Singleton.GetInstance(); // in another module
and the result is mySingleton1 = mySingleton2

Nessun commento:

Posta un commento