Wednesday, July 20, 2016

Design patterns c#

Design patterns c#

Singleton pattern

When we want only one instance of the object to be created and shared between clients (global variables of project)

To achieve/implement singleton pattern

1. Define the constructor as private, so no instance/object can be created
2. Define instance (variables) and methods as static. This will cause one global instance to be created and shared across.

E.g.

Public class clsSingleton
{
  public static int intCounter;
  private clsSingleton()
    {
       //This is a private constructor
     }

   public static void Hits()
    {
         intCounter++;
     }
    public static int getTotalHits()
     {
        return intCounter;
      }
}

Client Code
clsSingleton.Hit();                 //Everytime counter increments by 1


Factory Pattern

public class clsFactoryInvoice
{
  public static IInvoice getInvoice(int intInvoiceType)
  {
    IInvoice objInv;
    if(intInvoiceType == 1)
    {
      objInv = new clsInvoiceWithHeader();
    }
    else if (intInvoiceType ==2)
    {
        objInv = new clsInvoiceWithoutHeader();
     }
     else
      { return null;}
    return objInv;
  }
}

public interface IInvoice
{
  public void print();
}

public class clsInvoiceWithHeader : IInvoice
{
  public void print()
  {
     console.writelinne("Invoice will be printed with header");
   }
}

public class clsInvoiceWithoutHeader : IInvoice
{
  public void print()
  {
     console.writelinne("Invoice will be printed without header");
   }
}


Benefits : Client no need to know which all concrete classes available (loosely coupled) client will have object created just by passing parameter.

No comments:

Post a Comment