Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Chain of Responsibility design pattern example
namespace ChainOfResponsibility
{
//Handler class
public abstract class Approver
{
public abstract void HandleRequest(int requestAmount);
protected Approver NextApprover;
public void SetNextApprover(Approver approver)
{
NextApprover = approver;
}
}
}
using System;
namespace ChainOfResponsibility
{
//Concrete Handler class
public class Director : Approver
{
public override void HandleRequest(int requestAmount)
{
if (requestAmount < 300000)
Console.WriteLine("Director has approved amount - {0}", requestAmount);
else if (NextApprover != null)
NextApprover.HandleRequest(requestAmount);
}
}
}
using System;
namespace ChainOfResponsibility
{
//Concrete Handler class
public class Manager : Approver
{
public override void HandleRequest(int requestAmount)
{
if (requestAmount < 100000)
Console.WriteLine("Manager has approved amount - {0}", requestAmount);
else if (NextApprover != null)
NextApprover.HandleRequest(requestAmount);
}
}
}
using System;
namespace ChainOfResponsibility
{
class Program
{
//Client Class
static void Main(string[] args)
{
//Create classes of chain of responsibility
Approver Manager = new Manager();
Approver SeniorManager = new SeniorManager();
Approver Director = new Director();
//Set next request approver or handler
Manager.SetNextApprover(SeniorManager);
SeniorManager.SetNextApprover(Director);
//Create requests.
Manager.HandleRequest(75000);
Manager.HandleRequest(150000);
Manager.HandleRequest(250000);
Console.ReadLine();
}
}
}
using System;
namespace ChainOfResponsibility
{
//Concrete Handler class
public class SeniorManager : Approver
{
public override void HandleRequest(int requestAmount)
{
if (requestAmount < 200000)
Console.WriteLine("Senior Manager has approved amount - {0}", requestAmount);
else if (NextApprover != null)
NextApprover.HandleRequest(requestAmount);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment