The idea of the pattern is to decouple the sender of a request from the receiver of that request. Essentially the sender is unaware of the chain of handlers; each handler may pass on the request to the next handler in the chain.

Here is a straight forward example to start with. It can most likely be refined.

package pattern
/** Define a class to represent requests.  Most likely a case class of some kind */
class Request
/** A request to print a string */
case class PrintRequest(message : String) extends Request
 
/** Base class for handlers */
class RequestHandler (private val successor : Option[RequestHandler]) {
 
/** Default implementation calls successor if it exists */
def handle(request : Request) {
  for (s <- successor) s.handle(request)
  }
}
}
 
/** This specific handler print requests for strings that start with "1" */
class OneHandler(successor : RequestHandler) extends RequestHandler(Some(successor)) {
  override def handle(request : Request) {
    request match {
      case PrintRequest(s) => 
        if (s startsWith "1")
          println("One handled: " + s)
        else
            super.handle(request)
      case _ =>
          super.handle(request)
    }
  }
}
 
/** This is a stop-gap handler.  It prints anything */
class CatchAllHandler extends RequestHandler(None) {
  override def handle(request : Request) {
    request match {
      case PrintRequest(s) => 
          println("CatchAll handled: " + s)
      case _ =>
          super.handle(request)
    }
  }
}
 
object Chain {
  def main(args : Array[String]) {
    // construct a handler chain.  Like the handlers
    // the chain is a fabrication to demonstrate the pattern
    val rh : RequestHandler = 
    new OneHandler (new CatchAllHandler)
    val requestOne = new PrintRequest("1 is better than zero")
    val requestTwo = new PrintRequest("but two is better than one")
    rh handle requestOne
    rh handle requestTwo
  }
}
 
patterns/gofchainofresponsibility.txt · Last modified: 2010/02/11 09:10
 
Recent changes RSS feed Valid XHTML 1.0 Driven by DokuWiki