통역
: 원본이 되는 것을 다른 형태로 변경함. 자주 사용하는 문제, 문법 등을 정의하고 이 문법에 맞춰 대입하여 문제를 해결한다. 정규 표현식
등이 해당된다.
public class PostfixNotation {
private final String expression;
public PostfixNotation (String expression) {
this.expression = expression;
}
public static void main(String[] args) {
PostfixNotation postfixNotation = new PostfixNotation("123+-");
postfixNotation.calculate();
//TODO
}
private void calculate() {
Stack<Integer> numbers = new Stack<>();
for(char : this.expression.toCharArray()) {
switch (c) {
case '+':
numbers.push(numbers.pop() + numbers.pop());
break;
case '-':
int right = numbers.pop();
int left = numbers.pop();
numbers.push(left - right);
break;
default:
numbers.push(Integer.parseInt(c + ""));
}
}
}
public class App {
public static void main(String[] args) {
PostfixExpression expression = PostfixParser.parse("xyz+-");
int result = expression.interpret(Map.op('x', 1, 'y', 2, 'z', 3));
}
}
public interface PostfixExpression {
int interpret(Map<Character, Integer> context);
}
public class VariableExpression implements PostfixExpression {
private Character variable;
public VariableExpression(Character variable) {
this.variable = variable;
}
@Override
public int interpret(Map<Character, Integer> context) {
return context.get(variable);
}
}
public class PostfixParser {
public static PostfixExpression parse (String expression) {
Stack<PostfixExpression> stack = new Stack<>();
for(char c : expression.toCharArray()) {
stack.push(getExpression(c, stack));
}
return stack.pop();
}
private static PostfixExpression getExpression (char c, Stack<PostfixExpression> stack) {
switch(c) {
case '+':
return new PlusExpression(stack.pop(), stack.pop());
case '-':
PostfixExpression right = stack.pop();
PostfixExpression left = stack.pop();
return new MinusExpression(left, right);
default:
return new VariableExpression(c);
}
}
}
Expression
과 Parser
가 복잡해진다.
정규표현식
Pattern.matches("[a-z]{6}", "spring");
Expression language
- SPEL
레퍼런스 참고하기Book book = new Book("spring");