Thursday, April 16, 2009

Design pattern: Chain of responsibility (COR)



Design pattern: Chain of responsibility (COR)


COR is a software coding practice used by the "Gang of Four". It comes under the behavioral category since for each request the behavior of the object would be different.


A good example could be a Help software module; For instance there are three buttons, red blue and green , on a user interface. And for each button-click the system shall show a message box with the related helpful text. So, when red button is click the a help command is routed to each of the object on the user interface (all of the buttons and UI itself in this case) and that object is going to decided if it has to process the request or pass it on to the next object.


FIG 1: Chain of responsibility design


Similar would be the case when the UI will be clicked; the message will route to all of the objects and would eventually be handled by the UI object.


This promotes loose coupling between sender of a request and its receiver by giving more than one object an opportunity to handle the request.

Main program calls the chain as follows:

int nRequest = 1;//Could be 1 = multiply, 2 = divide, 3= add, etc.
(new CSubtractChn(new CAddChn(new CMultiplyChn(new CNoopChn())))).HandleRequest(1);


Following handles the multiply request,

public class CMultiplyChn : CChain
{
public CMultiplyChn() { }
public CMultiplyChn(CChain nextChain)
{
AddNextInChain(nextChain); //Add the next in chain
}

public override void HandleRequest(int nRequest)
{
CHelper.Msg("Checking multipy");
switch (nRequest)
{
case 1:
CHelper.Msg("Found request 1, processing... multiply done.");
break;
default:
if (m_NextInChain != null)
{
CHelper.Msg("Nexting...");
m_NextInChain.HandleRequest(nRequest);
}

break;

}
}

Following is the base chain class,

public abstract class CChain
{
protected CChain m_NextInChain;

///
/// Adds the next in chain
///

///
public void AddNextInChain(CChain theChain)
{
m_NextInChain = theChain;
}

///
/// Abstract: Must implement all derived classes
///

///
public abstract void HandleRequest(int nRequest);

}

Related Posts

Popular Posts