Thursday, January 10, 2008

* Patterns : ChainOfResponsibility Behavioral Pattern

ChainOfResponsibility Behavioral Pattern helps achieving loose coupling between request sender and receiver object.

It helps in introducing a set of chained interceptor objects which can handle the request or pass it to next member in chain. The chaining can be pre-configured or can be done by client before invoking the chain.

Consider the below class diagram:

ChainOfResponsibility

Based on the base exception handler, a set of concrete exception handlers are created. Now client can chain them based on how specific handling of exception is required.

BaseExceptionHandler sqlHandler, securityHandler, allHandler;
public void Run()
{
    sqlHandler = new SqlExceptionHandler();
    securityHandler = new SecurityExceptionHandler();
    allHandler = new AllExceptionHandler();

    sqlHandler.SetSuccessor(securityHandler);
    securityHandler.SetSuccessor(allHandler);

    Exception ex = new Exception();
    sqlHandler.HandleException(ex);
}

Additional handlers can be configured in between or at the end.

It chains the receiving objects and pass the request along the chain until an object handles it.

Download code of ChainOfResponsibility Behavioral Pattern

Other Design Patterns

1 comment:

  1. some examples existing in .net framework code would be nice.

    ReplyDelete