শনিবার, ১৬ নভেম্বর, ২০১৩

Singleton Pattern



  •  One of the simplest patterns
  •  Creational pattern.
  •  GB pattern Gi gva¨‡g ensure Kiv nq †h GKwU class Gi GKwU gvÎ instance _vK‡e Ges Dnv‡Z access Gi Rb¨ GKwU global access point _vK‡e hv Øviv Dnv‡Z access Kiv hv‡e|
UML Diagram:



  •  Singleton class Gi GKwU private static constructor _vK‡e.
  •  class G GKwU static method _vK‡e hvnv public type Gi Ges Dnv‡K wewfbœ hvqMvq call Kiv hv‡e|
 


Real life example
  • United States Gi President office Singleton Kvib United States Constitution Abyhvqx GKB mg‡q Zv‡`i ‡`‡k GKRb gvÎ President _vK‡Z cvi‡e|
  •  myZivs †h‡Kvb mgq GKRb e¨vw³B President wnmv‡e _vK‡eb|
  • myZivs wZwbB The President of the United States global point Øviv office G access Ki‡eb



Figure : Object Diagram for Singleton using Presidency Example

Steps for implement the Singleton:

Step 1: Create a Singleton Class.
SingleObject.cs
public class SingleObject
{

    //create an object of SingleObject
    private static SingleObject instance = new SingleObject();

    //make the constructor private so that this class cannot be
    //instantiated
    private SingleObject() { }

    //Get the only object available
    public static SingleObject getInstance()
    {
        return instance;
    }

    public void showMessage(){
     Console.WriteLine("Hello World!");
   }
}

Step 2: Get the only object from the singleton class.

SingletonPatternDemo.cs
public class SingletonPatternDemo
{
    public static void main(String[] args) {

      //illegal construct
      //Compile Time Error: The constructor SingleObject() is not visible
      //SingleObject object = new SingleObject();

      //Get the only object available
      SingleObject iobject = SingleObject.getInstance();

      //show the message
      iobject.showMessage();
   }
}

Step 3: Verify the output.
Hello World!
 


কোন মন্তব্য নেই:

একটি মন্তব্য পোস্ট করুন