Open leeyuunsung opened 2 years ago
public class App {
public static void main(String[] args) {
PostfixExpression expression = PostfixParser.parse("xyz+-a+");
int result = expression.interpret(Map.of('x', 1, 'y', 2, 'z', 3, 'a', 4));
System.out.println(result);
}
}
public interface PostfixExpression {
int interpret(Map<Character, Integer> context);
}
public class VariableExpression implements PostfixExpression {
private Character character;
public VariableExpression(Character character) {
this.character = character;
}
@Override
public int interpret(Map<Character, Integer> context) {
return context.get(this.character);
}
}
public class PlusExpression implements PostfixExpression {
private PostfixExpression left;
private PostfixExpression right;
public PlusExpression(PostfixExpression left, PostfixExpression right) {
this.left = left;
this.right = right;
}
@Override
public int interpret(Map<Character, Integer> context) {
return left.interpret(context) + right.interpret(context);
}
}
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);
}
}
}
public interface PostfixExpression {
int interpret(Map<Character, Integer> context);
static PostfixExpression plus(PostfixExpression left, PostfixExpression right) {
return context -> left.interpret(context) + right.interpret(context);
}
static PostfixExpression minus(PostfixExpression left, PostfixExpression right) {
return context -> left.interpret(context) - right.interpret(context);
}
static PostfixExpression variable(Character c) {
return context -> context.get(c);
}
}
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 plus(stack.pop(), stack.pop());
case '-':
PostfixExpression right = stack.pop();
PostfixExpression left = stack.pop();
return minus(left, right);
default:
return variable(c);
}
}
}
인터프리터 패턴 1부 - 패턴 소개
예시
참고
1 + 2 - 5
와 같이 부호가 숫자 중간에 위치한 형태는 infix 에 해당1 2 + 5 -
와 같이 부호가 숫자 오른쪽에 위치한 형태는 postfix 에 해당123+-
의 경우 부호가 위치한 경우 앞의 두 숫자를 연산1(23+)-
->15-
->-4
123+-
과 같이xyz+-
패턴을 자주 사용하는 경우, DSL(Domain Specific Language) 로써 등록하고 정의하여 사용할 수 있다인터프리터 패턴 아키텍처
xyz+-
)xyz
)+-
)