Chain Of Responsibility design pattern is a behavioral design pattern used to free our main stream code from if-else blocks and make the main stream scalable by freeing it from code clutter and making it more loosely coupled.
Let’s try to exemplify the loan requirement scenario of a bank customer.Let’s say you need some loan and go to the bank and first need a loan of 5000 TL to an individual customer representative.
Suppose the bank grants certain authorized persons the authority to approve a certain amount of credit in order to approve the loan when granting a loan..
Personal Customer Representative –> until 5.000$,
Branch manager–> until 10.000 – 15.000$
Ceneral manager –> until 15.000 – 35.000$
be able to approve loans.
public class Credit
{
private double _amount;
public Credit(double amount)
{
this._amount = amount;
}
public double Amount
{
get { return _amount; }
set { _amount = value; }
}
}
public abstract class Approver
{
protected Approver successor;
public void SetSuccessor(Approver successor)
{
this.successor = successor;
}
public abstract void Approve(Credit purchase);
}
public class PersonalCustomerRepresentative : Approver
{
public override void Approve(Credit credit)
{
if (credit.Amount < 5000)
{
Console.WriteLine("{0} approved request# {1}",
this.GetType().Name, credit.Amount);
}
else if (successor != null)
{
successor.Approve(credit);
}
}
}
public class BranchManager : Approver
{
public override void Approve(Credit credit)
{
if (credit.Amount < 25000.0)
{
Console.WriteLine("{0} approved request# {1}",
this.GetType().Name, credit.Amount);
}
else if (successor != null)
{
successor.Approve(credit);
}
}
}
public class GeneralManager : Approver
{
public override void Approve(Credit credit)
{
if (credit.Amount > 15000.0 && credit.Amount < 30000.0)
{
Console.WriteLine("{0} approved request# {1}",
this.GetType().Name, credit.Amount);
}
else
{
Console.WriteLine(
"Request# {0} The application could not be approved because the loan amount is high!",
credit.Amount);
}
}
}
class Program
{
static void Main(string[] args)
{
// Setup Chain of Responsibility
Approver julia = new PersonalCustomerRepresentative();
Approver nicole = new BranchManager();
Approver tomy = new GeneralManager();
julia.SetSuccessor(nicole);
nicole.SetSuccessor(tomy);
// Generate and process purchase requests
Credit p = new Credit(25000);
julia.Approve(p);
// Wait for user
Console.ReadKey();
}
}
Output: GeneralManager approved request# 25000
İlk Yorumu Siz Yapın