Java
Usage examples: The Chain of Responsibility is pretty common in Java.
One of the most popular use cases for the pattern is bubbling events to the parent components in GUI classes. Another notable use case is sequential access filters.
Here are some examples of the pattern in core Java libraries:
Identification: The pattern is recognizable by behavioral methods of one group of objects that indirectly call the same methods in other objects, while all the objects follow the common interface.
Filtering access
This example shows how a request containing user data passes a sequential chain of handlers that perform various things such as authentication, authorization, and validation.
This example is a bit different from the canonical version of the pattern given by various authors. Most of the pattern examples are built on the notion of looking for the right handler, launching it and exiting the chain after that. But here we execute every handler until there’s one that can’t handle a request. Be aware that this still is the Chain of Responsibility pattern, even though the flow is a bit different.
middleware
middleware/Middleware.java: Basic validation interface
package refactoring_guru.chain_of_responsibility.example.middleware;
/**
* Base middleware class.
*/
public abstract class Middleware {
private Middleware next;
/**
* Builds chains of middleware objects.
*/
public static Middleware link(Middleware first, Middleware... chain) {
Middleware head = first;
for (Middleware nextInChain: chain) {
head.next = nextInChain;
head = nextInChain;
}
return first;
}
/**
* Subclasses will implement this method with concrete checks.
*/
public abstract boolean check(String email, String password);
/**
* Runs check on the next object in chain or ends traversing if we're in
* last object in chain.
*/
protected boolean checkNext(String email, String password) {
if (next == null) {
return true;
}
return next.check(email, password);
}
}middleware/ThrottlingMiddleware.java: Check whether the limit on the number of requests is reached
middleware/UserExistsMiddleware.java: Check user’s credentials
middleware/RoleCheckMiddleware.java: Check user’s role
server
server/Server.java: Authorization target
Demo.java: Client code
OutputDemo.txt: Execution result
Last updated