2007 |
Section 1, Chapter 3 |
Chain of Responsibility Pattern
Concept
It makes sure each member in a chain controls when and to what class it hands its processing to. The pattern controls the code flow by using inheritance and by allowing instances of its predecessors to be loaded one inside the other, forming in effect a chain of classes that hand off to the next class in the chain at the end of its turn.
Use
If you have a group of classes that are all interdependent on each other and each performs a particular piece of processing
Design
Handler: The handler object encapsulates the entire chain of handler instances inside each other instance. In other words, the first link in the chain contains the next and that link contains each consecutive link.
Illustration
abstract class Process
{
private Process _nextProcess;
protected abstract void RunNext();
public void Run()
{
RunNext();
if(_nextProcess != null)
{
_nextProcess.Run();
}
}
public void SetNextProcess(Process process)
{
_nextProcess = process;
}
}
class FirstProcess : Process
{
protected override void RunNext()
{
System.Threading.Thread.Sleep(1000);
}
}
class SecondProcess : Process
{
protected override void RunNext()
{
System.Threading.Thread.Sleep(2000);
}
}
class ThirdProcess : Process
{
protected override void RunNext()
{
System.Threading.Thread.Sleep(3000);
}
}
Process firstProcess = new FirstProcess();
Process secondProcess = new SecondProcess();
Process thirdProcess = new ThirdProcess();
firstProcess.SetNextProcess(secondProcess);
secondProcess.SetNextProcess(thirdProcess);
thirdProcess.SetNextProcess(null);
firstProcess.Run();