public interface Command { String CMD_MENU_SAVE = "menu.save"; }
命令操作系统:
public abstract class OperateSystem { private static final Map<String, Function<JSONObject, ?>> COMMAND_MAP = new HashMap<>();
public static <T, R> void registerCommand(String command, Class<T> paramType, Function<T, R> receiver) { COMMAND_MAP.put(command, json -> { T param = json.toJavaObject(paramType); if (ObjectUtils.isEmpty(param)) { throw new CommonException("Parameter parsing failed, expected type: %s", paramType.getName()); }
String message = BeanUtils.parseEmptyField(param); if (StringUtils.isNotBlank(message)) { throw new CommonException("Parameter validation failed: %s", message); }
return receiver.apply(param); }); }
public static void unregisterCommand(String command) { COMMAND_MAP.remove(command); }
public static <R> R execute(String command, JSONObject param) { Function<JSONObject, R> function = getJsonFunction(command); return function.apply(param); }
@SuppressWarnings("unchecked") private static <R> Function<JSONObject, R> getJsonFunction(String command) { Function<JSONObject, R> function = (Function<JSONObject, R>) COMMAND_MAP.get(command); if (ObjectUtils.isEmpty(function)) { throw new CommonException("Unregistered command: %s", command); } return function; }
@SuppressWarnings("unchecked") public static <R, E> E execute(String command, Class<E> resultType, JSONObject param) { if (ObjectUtils.isEmpty(resultType)) { throw new CommonException("Command result type can not be null: %s", command); }
Function<JSONObject, R> function = getJsonFunction(command); R result = function.apply(param); if (ObjectUtils.isEmpty(result)) { return null; }
if (resultType.isInstance(result)) { return (E)result; }
throw new CommonException("Command [%s] failed to produce the expected result." + " Expected type: %s, Actual type: %s", command, resultType.getName(), result.getClass().getName()); }