Wednesday, August 3, 2016

Design patterns c# examples

Singleton Pattern

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

To achieved/implement Singleton pattern
1. Define the constructor as private. So no instance/object can be created
2. Define instance (variables) & 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 private constructor
}
private static void Hits()
{
intCounter++;
}
public static int getTotalHits()
{
return intCounter;
}
}

Client code

clsSingleTon.Hit();  // Everytime counter increments tag by 1

=========================================================================

Factory Pattern

public class clsFactoryInvoice
{
public static IInvoice getInvoice(int intInvoiceType)
{
IInvoice objinv;
if(intInvoiceType == 1)
{
objinv = new clsInvoiceWithHeaders();
}
else if (intInvoiceType == 2)
{
objinv = new clsInvoiceWithoutHeaders();
}
else
{
return null;
}
return objinv;
}
}

public Interface IInvoice
{
void print();
}

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

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

client code

class program
{
static void Main (string [] args)
{
int intInvoiceType = 0;
IInvoice objInvoice;
console.writeline("Enter Invoice Type");
intInvoiceType = console.readline();
objInvoice = clsFactoryInvoice.getInvoice(intInvoiceType );
objInvoice .print();
console.Readline();
}
}

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

No comments:

Post a Comment