Thursday, May 27, 2010

Software Design Patterns(C# Design Patterns)-Part I

C# Patterns(Software Design Pattren)


Software design patterns are mainly classified into three types.
1.Creational Pattern.
2.Structural Pattern.
3.behaviour Pattern.




Creational Patterns: It deals with the best way in dealing objects.
1. Singleton Pattern:
The singleton design pattern is used when only one instance of an object is needed throughout the lifetime of an application. The singleton class is instantiated at the time of first access and the same instance is used thereafter till the application quits.


C# Implementation
//Creational Pattern: SINGLETON
//Implemenation in C#
//By aravindbenator@gmail.com
/*The constructor should be private. Provide a static method, which returns an instance of the class. use a static variable to check whether already one instance is created or not. if already an instance is there , returns a null */
using System;
class SingleInstanceClass
{
private static SingleInstanceClass sic= null;
private static bool instanceFlag = false;

private SingleInstanceClass()
{
}
public static SingleInstanceClass Create()
{
if(! instanceFlag)
{
sic = new SingleInstanceClass();
instanceFlag = true;
return sic;
}
else
{
return null;
}
}
protected void Finalize()
{
instanceFlag = false;
}
}
class MyClient
{
public static void Main()
{
SingleInstanceClass sic1,sic2;
sic1 = SingleInstanceClass.Create();
if(sic1 != null)
Console.WriteLine("OK");
sic2 = SingleInstanceClass.Create();
if(sic2 == null)
Console.WriteLine("NO MORE OBJECTS");
}
}


2. Factory Method Pattern: Provides simple decision making class that can return object of one or more subclasses.
It includes defining an interface for creating an object.
Example:


//Creational Pattern: The Factory Method
//Author: aravindbenator@gmail.com
/* In Factory method pattern, A Factory class contains a factory method is used for creating the object. This factory method can be either static or non-static. */
using System;
class Factory
{
public Base GetObject(int type)
{
Base base1 = null;
switch(type)
{
case 1:
base1 = new Derived1();
break;
case 2:
base1 = new Derived2();
break;
}
return base1;
}
}
interface Base
{
void DoIt();
}
class Derived1 : Base
{
public void DoIt()
{
Console.WriteLine("Derived 1 method");
}
}
class Derived2 : Base
{
public void DoIt()
{
Console.WriteLine("Derived 2 method");
}
}
//Client class
//Client class needn’t know about instance creation. The creation of Product is //deferred to the Factory class
class MyClient
{
public static void Main()
{
Factory factory = new Factory();//Decides which object must create.
Base obj = factory.GetObject(2);
obj.DoIt();
}
}



aravindbenator@gmail.com

No comments:

Post a Comment