How to use this

ChainOfResponsability pattern

Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.

chain094.gif

This framework helps to create a chain of responsability. First your handler object must implement ILink<T> where T is the type of your base calss. In my sample I have an ICommand.

  public interface ICommand : ILink<ICommand>
  {
    void Execute();
  }

I implemented two command like this :

  public class Command1 : ICommand
  {
    public void Execute()
    {
      Console.WriteLine("Command 1");
      if (NextInChain != null) NextInChain.Execute();
    }

    public ICommand NextInChain { get; set; }
  }

  public class Command2 : ICommand
  {
    private readonly string _message;

    public Command2(string message)
    {
      _message = message;
    }

    public Command2()
    {
    }

    public void Execute()
    {
      Console.WriteLine("Command 2 " + _message);
      if (NextInChain != null) NextInChain.Execute();
    }

    public ICommand NextInChain { get; set; }
  }


Then you can easily create a chain like this:

      var chain = new Chain<ICommand>()
        .Add<Command1>()
        .Add<Command2>(() => new Command2("Test"))
        .Build();

      chain.Execute();

Last edited Mar 27, 2013 at 1:02 AM by decarufe, version 5

Comments

No comments yet.