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.

| What is the need for Bridge Pattern in C#? | What is the need for Builder Pattern in C#? | What is the need for Chain of Responsibility Pattern in C#? | What is the need for Command Pattern in C#? | What is the need for Composite Pattern in C#? | What is the need for Decorator Pattern in C#? | What is the need for Flyweight Pattern in C#? | What is the need for Interpreter Pattern in C#? | What is the need for Iterator Pattern in C#? | What is the need for Mediator Pattern in C#? | What is the need for Memento Pattern in C#? | What is the need for Prototype Pattern in C#? | What is the need for State Pattern in C#? | What is the need for Strategy Pattern in C#? | What is the need for Template Method Pattern in C#? | What is the need for unsafe code in C#? | What is the purpose of assert() in C#? | What is the purpose of AutoResetEvent in .NET? | What is the purpose of Console.ReadLine() in C#? | What is the purpose of machine.config file in .NET? |


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.