When implementing the Chain of Responsibility template, I came across a dilemma on how to transfer data between objects in the chain. The types of data transferred between an object in a chain may vary for each object. As a temporary fix, I created a Static class containing a stack, where each object in the chain can push the results onto the stack, and the next object in the chain can push the results from the stack. Here is an example of the code that I implemented.
public interface IHandler
{
IHandler Successor {get; set; }
void Process();
}
public static class StackManager
{
public static Stack DataStack = new Stack();
}
public class OpsA : IHandler
{
public IHandler Successor {get; set; }
public void Process()
{
var ProcessedData = DoSomeOperation();
StackManager.DataStack.Push(ProcessedData);
if(Successor != null) Successor();
}
}
public class OpsB : IHandler
{
public IHandler Successor {get; set; }
public void Process()
{
var InputData = StackManager.DataStack.Pop();
var NewProcessedData = DoMoreProcessing(InputData);
StackManager.DataStack.Push(NewProcessedData);
if(Successor != null) Successor();
}
}
public class ChainOfResponsibilityPattern
{
public void Process()
{
IHandler ProcessA = new OpsA();
IHandler ProcessB = new OpsB();
ProcessA.Successor = ProcessB;
ProcessA.Process();
}
}
Please help me find the best approach for transferring data between handlers in the chain.
source
share