public abstract class RequestHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(RequestHandler.class);
private RequestHandler next;
public RequestHandler(RequestHandler next) { this.next = next; }
public void handleRequest(Request req) { if (next != null) { next.handleRequest(req); } }
protected void printHandling(Request req) { LOGGER.info("{} handling request \"{}\"", this, req); }
@Override public abstract String toString(); }
public class OrcCommander extends RequestHandler {
public OrcCommander(RequestHandler handler) { super(handler); }
@Override public void handleRequest(Request req) { if (RequestType.DEFEND_CASTLE == req.getRequestType()) { printHandling(req); req.markHandled(); } else { super.handleRequest(req); } }
@Override public String toString() { return "Orc commander"; } }
public class OrcOfficer extends RequestHandler {
public OrcOfficer(RequestHandler handler) { super(handler); }
@Override public void handleRequest(Request req) { if (RequestType.TORTURE_PRISONER == req.getRequestType()) { printHandling(req); req.markHandled(); } else { super.handleRequest(req); } }
@Override public String toString() { return "Orc officer"; }
}
public class OrcSoldier extends RequestHandler {
public OrcSoldier(RequestHandler handler) { super(handler); }
@Override public void handleRequest(Request req) { if (RequestType.COLLECT_TAX == req.getRequestType()) { printHandling(req); req.markHandled(); } else { super.handleRequest(req); } }
@Override public String toString() { return "Orc soldier"; } }
public class OrcKing {
private RequestHandler chain;
public OrcKing() { buildChain(); }
private void buildChain() { chain = new OrcCommander(new OrcOfficer(new OrcSoldier(null))); }
public void makeRequest(Request req) { chain.handleRequest(req); }
}
public enum RequestType {
DEFEND_CASTLE, TORTURE_PRISONER, COLLECT_TAX
}
public class Request {
private final RequestType requestType;
private final String requestDescription;
private boolean handled;
public Request(final RequestType requestType, final String requestDescription) { this.requestType = Objects.requireNonNull(requestType); this.requestDescription = Objects.requireNonNull(requestDescription); }
public String getRequestDescription() { return requestDescription; }
public RequestType getRequestType() { return requestType; }
public void markHandled() { this.handled = true; }
public boolean isHandled() { return this.handled; }
@Override public String toString() { return getRequestDescription(); }
}
public class App {
public static void main(String[] args) {
var king = new OrcKing(); king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle")); king.makeRequest(new Request(RequestType.TORTURE_PRISONER, "torture prisoner")); king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax"));
} }
|