What is the need for Chain of Responsibility Pattern in C#?Generally
the sender and receiver will be strongly coupled. If you prefer to avoid
it then you can implement Chain of Responsibility Pattern where in, message
sent by sender can be received by a set of objects existing in the chain,
and one object from this chain will be handling the request message sent
by the sender. Here is a code snippet showing creation of chain of receivers:
class testClass { public static void Main() { receiver rObj1 = new derivedReceiver1(); receiver rObj2 = new derivedReceiver2(); receiver rObj3 = new derivedReceiver3(); rObj1.addToChain(rObj2); rObj2.addToChain(rObj3); int[] reqFromSender = {5, 20, 12, 40, 23, 60, 45, 34, 32}; foreach(int singleReq in reqFromSender) { rObj1.processRequest(singleReq); } } } public class receiver { protected receiver nextObjInChain; public void addToChain(receiver rObj) { nextObjInChain = rObj; } public virtual void processRequest(int reqData) { //Have a computational logic to decide whether the request can be processed. //You can also pass the request to the next object in the chain as shown below: if(nextObjInChain != null) { nextObjInChain.procesRequest(reqData); } } } In the above shown code, the processRequest method of receiver class passes the request to the next object in the chain. You can define derivedReceiver1, derivedReceiver2 and derivedReceiver3 classes which are all derived from receiver class. In these classes, you can override processRequest method to add conditions which when evaluated to true, the request can be processed. If not, the request can be moved to the next object in chain.
|