Behavioral Patterns - Chain of Responsibility Pattern Exercise
The Chain of Responsibility Pattern is very useful to avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along with the chain until an object handles it. We will implement a naïve security filter chain using this pattern in our practice exercise. You will certainly enjoy this exercise as it is a great way to get you totally master this pattern.
Reading Materials
- https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern (15 minutes reading)
Practice Materials
- Use chain of responsibility pattern to create a naive security filter chain that will check the following responsibilities in order:
- If any endpoint matches the request
- False - return Not Found
- If the endpoint has any security rules
- False - return Resource
- If the request contains any authorization header
- False - return Unauthorized request
- If the authorization is approved
- False - return Invalid authorization
- return Resource
Components
- Handler (Interface for handling requests)
- ConcreteHandler (Handle the request it is the responsibility for or forwards it to its successor)
- Client (Initiate the request to a ConcreteHandler object on any part of the chain, in this example, it should start from the the first filter)
Tips
- you may create a Helper class to handle some conditional logic
Solution
Questions to discuss
- What are the common use cases to apply a Chain of Responsibility?
- What features are there in the application when you see that you should apply the Chain of Responsibility pattern?
Comments
Post a Comment