|
| 1 | +@Getter |
| 2 | +public class Request { |
| 3 | + |
| 4 | + private final RequestType requestType; |
| 5 | + private final String requestDescription; |
| 6 | + private boolean handled; |
| 7 | + |
| 8 | + public Request(final RequestType requestType, final String requestDescription) { |
| 9 | + this.requestType = Objects.requireNonNull(requestType); |
| 10 | + this.requestDescription = Objects.requireNonNull(requestDescription); |
| 11 | + } |
| 12 | + |
| 13 | + public void markHandled() { |
| 14 | + this.handled = true; |
| 15 | + } |
| 16 | + |
| 17 | + @Override |
| 18 | + public String toString() { |
| 19 | + return getRequestDescription(); |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +public enum RequestType { |
| 24 | + DEFEND_CASTLE, TORTURE_PRISONER, COLLECT_TAX |
| 25 | +} |
| 26 | + |
| 27 | +public interface RequestHandler { |
| 28 | + |
| 29 | + boolean canHandleRequest(Request req); |
| 30 | + |
| 31 | + int getPriority(); |
| 32 | + |
| 33 | + void handle(Request req); |
| 34 | + |
| 35 | + String name(); |
| 36 | +} |
| 37 | + |
| 38 | +@Slf4j |
| 39 | +public class OrcCommander implements RequestHandler { |
| 40 | + @Override |
| 41 | + public boolean canHandleRequest(Request req) { |
| 42 | + return req.getRequestType() == RequestType.DEFEND_CASTLE; |
| 43 | + } |
| 44 | + |
| 45 | + @Override |
| 46 | + public int getPriority() { |
| 47 | + return 2; |
| 48 | + } |
| 49 | + |
| 50 | + @Override |
| 51 | + public void handle(Request req) { |
| 52 | + req.markHandled(); |
| 53 | + LOGGER.info("{} handling request \"{}\"", name(), req); |
| 54 | + } |
| 55 | + |
| 56 | + @Override |
| 57 | + public String name() { |
| 58 | + return "Orc commander"; |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +// OrcOfficer and OrcSoldier are defined similarly as OrcCommander ... |
| 63 | + |
| 64 | + |
| 65 | +public class OrcKing { |
| 66 | + |
| 67 | + private List<RequestHandler> handlers; |
| 68 | + |
| 69 | + public OrcKing() { |
| 70 | + buildChain(); |
| 71 | + } |
| 72 | + |
| 73 | + private void buildChain() { |
| 74 | + handlers = Arrays.asList(new OrcCommander(), new OrcOfficer(), new OrcSoldier()); |
| 75 | + } |
| 76 | + |
| 77 | + public void makeRequest(Request req) { |
| 78 | + handlers |
| 79 | + .stream() |
| 80 | + .sorted(Comparator.comparing(RequestHandler::getPriority)) |
| 81 | + .filter(handler -> handler.canHandleRequest(req)) |
| 82 | + .findFirst() |
| 83 | + .ifPresent(handler -> handler.handle(req)); |
| 84 | + } |
| 85 | +} |
| 86 | + |
| 87 | + public static void main(String[] args) { |
| 88 | + |
| 89 | + var king = new OrcKing(); |
| 90 | + king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle")); |
| 91 | + king.makeRequest(new Request(RequestType.TORTURE_PRISONER, "torture prisoner")); |
| 92 | + king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax")); |
| 93 | +} |
0 commit comments