Passing data between objects in Chain of Responsibility pattern

Posted by AbrahamJP on Stack Overflow See other posts from Stack Overflow or by AbrahamJP
Published on 2011-03-18T08:02:06Z Indexed on 2011/03/18 8:09 UTC
Read the original article Hit count: 280

Filed under:
|

While implementing the Chain of Responsibility pattern, i came across a dilemma om how to pass data between objects in the chain. The datatypes passed between object in the chain can differ for each object. As a temporary fix I had created a Static class containing a stack where each object in the chain can push the results to the stack while the next object in the chain could pop the results from the stack. Here is a sample code on what I had implemented.

public interface IHandler
{        
  void Process();        
}

public static class StackManager
{
  public static Stack DataStack = new Stack();
}

//This class doesn't require any input to operate
public class OpsA : IHandler
{
  public IHandler Successor {get; set; }
  public void Process()
   {
      //Do some processing, store the result into Stack
      var ProcessedData = DoSomeOperation();
      StackManager.DataStack.Push(ProcessedData);

      if(Successor != null) Successor();            
  }
}

//This class require input data to operate upon
public class OpsB : IHandler
{
  public IHandler Successor {get; set; }
  public void Process()
  {
      //Retrieve the results from the previous Operation
      var InputData =  StackManager.DataStack.Pop();

      //Do some processing, store the result into Stack
      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 to find a better approach to pass data between handlers objects in the chain.

© Stack Overflow or respective owner

Related posts about c#

Related posts about design-patterns