Chain of Responsibility Pattern : Chain Pattern « Design Patterns « C# / C Sharp






Chain of Responsibility Pattern

 

using System;
public abstract class Chain {

    protected Chain theNextInChain;
    public abstract void DealWithRequirement(string requirement);

    public void NextInChain(Chain next) {
        this.theNextInChain = next;
    }

}

public class Employee : Chain {
    public override void DealWithRequirement(string requirement) {
        switch (requirement) {
            case "Job":
                Console.WriteLine("{0} Staff", this);
                break;
            default:
                if (theNextInChain != null)
                    theNextInChain.DealWithRequirement(requirement);
                break;
        }
    }
}


public class Manager : Chain {
    public override void DealWithRequirement(string requirement) {
        switch (requirement) {
            case "Manager":
                Console.WriteLine("{0} requirement.", this);
                break;
            default:
                if (theNextInChain != null)
                    theNextInChain.DealWithRequirement(requirement);
                break;
        }
    }
}


public class Senior : Chain {
    public override void DealWithRequirement(string requirement) {
        switch (requirement) {

            default: Console.WriteLine("{0} has managed the " + requirement + " requirement.", this);
                break;
        }
    }

    public Senior() { ;}

}
class Client {
    static void Main(string[] args) {
        Chain staff = new Employee();
        Chain manager = new Manager();
        Chain seniorManager = new Senior();

        staff.NextInChain(manager);
        manager.NextInChain(seniorManager);

        staff.DealWithRequirement("Corporates");
        staff.DealWithRequirement("Job");
        staff.DealWithRequirement("Manager");
        staff.DealWithRequirement("Agency");
    }
}

 








Related examples in the same category