|
| 1 | +package com.luv2code.designpatterns.behavioral.interpreter.v2_advanced_with_and_expression; |
| 2 | + |
| 3 | +/** |
| 4 | + * Role: Helper (Parser) |
| 5 | + * |
| 6 | + * Parses a raw command string and builds the appropriate Expression. |
| 7 | + * |
| 8 | + * Not part of the GoF pattern itself ... this is the caller that constructs |
| 9 | + * and triggers the expressions. |
| 10 | + */ |
| 11 | +public class CommandParser { |
| 12 | + |
| 13 | + private static final String AND_SEPARATOR = " AND "; |
| 14 | + |
| 15 | + public Expression parse(String inputCommand) { |
| 16 | + |
| 17 | + if (inputCommand == null || inputCommand.isBlank()) { |
| 18 | + return new InvalidCommandExpression("empty input"); |
| 19 | + } |
| 20 | + |
| 21 | + String trimmedInput = inputCommand.trim(); |
| 22 | + |
| 23 | + // check for AND expressions |
| 24 | + int andIndex = trimmedInput.indexOf(AND_SEPARATOR); |
| 25 | + if (andIndex != -1) { |
| 26 | + // we found AND |
| 27 | + String leftInput = trimmedInput.substring(0, andIndex).trim(); |
| 28 | + String rightInput = trimmedInput.substring(andIndex + AND_SEPARATOR.length()).trim(); |
| 29 | + return new AndExpression(parse(leftInput), parse(rightInput)); |
| 30 | + } |
| 31 | + |
| 32 | + String[] parts = trimmedInput.split("\\s+", 2); |
| 33 | + |
| 34 | + String commandName = parts[0]; |
| 35 | + String argument = parts.length > 1 ? parts[1] : ""; |
| 36 | + |
| 37 | + return switch (commandName) { |
| 38 | + case "/join" -> new JoinExpression(argument); |
| 39 | + case "/mute" -> new MuteExpression(argument); |
| 40 | + case "/remind" -> new RemindExpression(argument); |
| 41 | + default -> new InvalidCommandExpression(commandName); |
| 42 | + }; |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | + |
| 47 | + |
| 48 | + |
| 49 | + |
| 50 | + |
| 51 | + |
| 52 | + |
| 53 | + |
| 54 | + |
| 55 | + |
0 commit comments