Chain of Responsibility Pattern

Chain of Responsibility Pattern: chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects.

In other words, when a request can be handled by giving more than one object a chance to handle the request.

Example: One example is lease request.

And the handlers are Team Leader ,Manager and Director.

Code is also available on GitHub. Click here to go to git hub repository.

namespace ChainOfResponsibility

{

class Program

{

static void Main(string[] args)

{

// Setup Chain of Responsibility

var h1 = new TeamLeader();

var h2 = new Manager();

var h3 = new Director();

h1.SetSuccessor(h2);

h2.SetSuccessor(h3)

 

// Generate and process request

int[] numberOfDaysRequested = { 2,7,4,12,8,5,3,14 };

foreach (int numberOfDays in numberOfDaysRequested)

{

h1.ApproveLeave(numberOfDays);

}

Console.ReadLine();

}

}

abstract class Handler

{

protected Handler successor;

public void SetSuccessor(Handler successor)

{

this.successor = successor;

}

 

public abstract void ApproveLeave(int numberOfDays);

}

class TeamLeader : Handler

{

public override void ApproveLeave(int numberOfDays)

{

if (numberOfDays < 5)

{

Console.WriteLine($”{numberOfDays} leave approved by TeamLeader”);

}

else if (successor != null)

{

successor.ApproveLeave(numberOfDays);

}

}

}

class Manager : Handler

{

public override void ApproveLeave(int numberOfDays)

{

if (numberOfDays >= 5 && numberOfDays <10)

{

Console.WriteLine($”{numberOfDays} leave approved by Manager”);

}

else if (successor != null)

{

successor.ApproveLeave(numberOfDays);

}

}

}

class Director : Handler

{

public override void ApproveLeave(int numberOfDays)

{

if (numberOfDays >=10)

{

Console.WriteLine($”{numberOfDays} leave approved by Director”);

}

else if (successor != null)

{

successor.ApproveLeave(numberOfDays);

}

}

}

chainofresponsibility_console
Chain of Responsibility Output

 

Author: Rupesh

Hi! I'm Rupesh, a funophile and technophile. I'm an Application Developer, Solution Architect and IT-Consultant, and an author in the works. I am a Microsoft certified Professional and Solution Developer (MCP and MCSD).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s