Sunday, September 13, 2009

Facade Pattern with C#

Facade Pattern classified into Structural Pattern is unified interface that represents entire by hiding the complexities.

It provides the higher level interface which makes subsystem easier to use. It provides client with a single entry point which eliminates knowing the complexity of many subsystems beneath it.


In this pattern, facade object is aware of the responsibility owned by subsystem classes. It essentially delegates the client request to subsystem classes; whereas sub-system classes perform operation as assigned by facade object and doesn’t holds any reference to it.


Below is the sample class diagram demonstrates Facade pattern where client makes a call to Facade class and the subsystem operations are managed by facade thereby eliminating the client to directly deal with subsystems.




 
Code for Facade Class:

namespace MyProject.FacadePattern
{
public class Facade

{
private IValidateUser _validateuser;
private IAddUser _adduser;
private INotifyService _notifyservice;

public Facade()
{
_validateuser = new ValidateUser();
_adduser = new AddUser();
_notifyservice = new NotifyService();
}

public bool AddUser(User user)
{
if (!_validateuser.ValidateUser(user))
return false;

_adduser.AddUser(user);
_notifyservice.SendEmail(user);
}
}
}


< Back to Design Patterns

Thursday, September 10, 2009

Decorator Pattern with C#

Decorator Pattern classified into Structural Pattern which add responsibilities to objects dynamically.

A client application often needs to augment the services provided by methods of some class, by inserting some pre and post-processing tasks before and after the method calls. If distinct pre and post-processing tasks were to be carried out for different clients, the application logic would become complex by conditional statements, leading to a maintenance nightmare.

Consider a class where clients can invoke method to transfer files to and from some remote server. In addition to being able to upload and download files, the client application would also like to log all file transfer requests and perform access checks for each invocation.

An implementation based on the Decorator pattern would derive a class from FileTransfer and override the virtual methods, inserting the additional operations before and after calling the base methods. Client still continue to call the same method; however additional responsibility is added to the class without affecting other clients using the same functionality. Thus, Decorator Pattern allows dynamic and transparent addition and removal of responsibilities without affecting client code.

FileTransfer Class (used by multiple clients):
namespace MyProject.DecoratorPattern
{
public class FileTransfer
{
public virtual bool UploadFile(string url)
{
bool result;
// File Upload Logic
Console.WriteLine("File Uploaded to url :" + url);
result = true;
return result;
}

public virtual bool DownloadFile(string url, string localpath)
{
bool result;
// File Download Logic
Console.WriteLine("File downloaded to '{0}' from url '{1}'", url, localpath);
result = true;
return result;
}
}
}



Derive from FileTransfer Class:
namespace MyProject.DecoratorPattern
{
class Decorator : FileTransfer
{
//Additional Responsibility added without affecting client code, demonstrate Decorator Pattern.
public override bool UploadFile(string url)
{
bool result = false;
if (!AccessAllowed(url)) return result;
result = base.UploadFile(url);
LogActivity(url);
return result;
}
//Additional Responsibility added without affecting client code, demonstrate Decorator Pattern.
public override bool DownloadFile(string url, string localpath)
{
bool result = false;
if (!AccessAllowed(url)) return result;
result = base.DownloadFile(url, localpath);
LogActivity(url);
return result;
}
private bool AccessAllowed(string url)
{
bool result;
// URL access Logic
Console.WriteLine("Access Allowed to url :" + url);
result = true;
return result;
}
private void LogActivity(string url)
{
// Logic to Log Upload/Download Activity
Console.WriteLine("Activity logged for url: " + url);
}
}
}


< Back to Design Patterns

Wednesday, September 9, 2009

Strategy Pattern with C#

Strategy Pattern classified under Behavioural Pattern encapsulates an algorithm inside a class.

Strategy Pattern is a class that has to perform strategically depending on user input, platform information and so on.. Depending on user input, a different algorithm will be used; however, the end result is the same.

To explain this through example, I have used three diferrent search algorighm, each with its own performance and accuracy trade-off. One of them is very computation-intensive, but does a more thorough job, while another is faster but generates results that may be inaccurate for very data. My application will ask the user for the desired performance and then invoke the appropriate algorithm. To this end, I will encapsulate my algorithms in classes that demonstrate Strategy Pattern.

iSearch.cs
This interface will be implemented by various classes with different search algorithm


namespace MyProject.StrategyPattern.Search
{
public interface iSearch
{
string Search(string keyword);
}
}



Search.cs
Having implemented all three algorithms in this manner mentioned below, I can now design the client that decouples it from the implementation details of any specific algorithm. The client holds a reference to the interface, and does not need to know anything about the concrete implementation of the interface.


namespace MyProject.StrategyPattern.Search
{

public class ListSearch : iSearch
{
#region iSearch Members

public string Search(string keyword)
{
return "Searched " + keyword + "with List Search Algorithm";
}

#endregion
}


public class TreeSearch : iSearch
{
#region iSearch Members

public string Search(string keyword)
{
return "Searched " + keyword + " with Tree Search Algorithm";
}

#endregion
}


public class BinarySearch : iSearch
{
#region iSearch Members

public string Search(string keyword)
{
return "Searched " + keyword + " Binary Search Algorithm";
}

#endregion
}

}


SearchKeyword.cs
Finally, I create an instance of the SearchKeyword class and, depending on user input, initialize it with the appropriate algorithm. The Test method of the SearchKeyword class invokes the Search method of the iSearch interface that every algorithm implements

namespace MyProject.StrategyPattern
{
public class SearchKeyword
{
private iSearch _search;

public SearchKeyword(iSearch Search)
{
_search = Search;
}

public string SearchString(string Keyword)
{
return _search.Search(Keyword);
}


}
}



< Back to Design Patterns

Tuesday, September 8, 2009

Singleton Pattern with C#

Singleton Pattern which is classified under Creational Pattern which focuses on having only one instance of object at any given time.

To give an example, windows directory service which has multiple entries but you can only have single instance of it through out the network.

  • A singleton is the sole instance of some class.
  • It is most often the case that the singleton should also be globally accessible, and this is achieved by making the creation method/property public.
  • Note that in the code below, the class constructor is private to avoind creating instance of class.
Creating Class which will return only one instance:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MyProject.SingletonSample.Evaluation;

namespace MyProject.SingletonSample
{
public class Singleton
{
// Private Constructor to not allow to creating instance
private Singleton() { }

private static iEvaluation instance;

// Creates and maintains single instance of Evaluation Class
public static iEvaluation Instance
{
get
{
if (instance == null)
{
instance = new Evaluation.Evaluation();
}
return instance;
}
}

}
}


Creating Instance of Singleton class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MyProject.SingletonSample.Evaluation;

namespace MyProject.SingletonSample
{
class Program
{
static void Main(string[] args)
{
EvalData ed1=new EvalData();
ed1.Name = "Aaaa";
ed1.Comment = "Added with ED1";
ed1.DateSubmitted = DateTime.Now;

EvalData ed2 = new EvalData();
ed2.Name = "Bbbb";
ed2.Comment = "Added with ED2";
ed2.DateSubmitted = DateTime.Now;

Singleton.Instance.AddEval(ed1);
Singleton.Instance.AddEval(ed2);

Console.ReadKey();
}
}
}

< Back to Design Patterns

Design Patterns

Design Patterns are recurring solution to recurring problems in software architecture. A design pattern can solve many problems by providing a framework for building an application.

Design patterns which make the design process cleaner and more efficient, are especially well-suited for object-oriented languages such as C#. Existing design patterns make good templates for the objects, allowing you to build software faster, re-use the code, and a pattern which is acceptable organisation wide.

Design patterns can improve the extensibility of your applications and the reuse of your objects. Software design and architecture without a rudimentary understanding of design patterns is unthinkable. Most software applications and systems incorporate one or more design patterns which we all might have come across, but don't know them as patterns.

A design pattern is a description of a set of interacting classes that provide a framework for a solution to a generalized problem in a specific context or environment. In other words, a pattern suggests a solution to a particular problem or issue in object-oriented software development

There are three basic classification of patters:

~ Creational
  1. Singleton Pattern
~ Structural, and
  1. Facade Pattern
  2. Decorator Pattern
~ Behavioural pattern
  1. Strategy Pattern