본문 바로가기

강의/Design pattern

인터프리터(Interpreter) 패턴

SMALL

Interpreter

통역 : 원본이 되는 것을 다른 형태로 변경함. 자주 사용하는 문제, 문법 등을 정의하고 이 문법에 맞춰 대입하여 문제를 해결한다. 정규 표현식 등이 해당된다.


Code Example

PostfixNotation

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 + ""));
			}
		}
	}

Code Example - 2

App

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));
	}
}

PostfixExpression

public interface PostfixExpression {
	int interpret(Map<Character, Integer> context);
}

TerminalExpression

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);
	}
}

PostfixParser

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`을 추가할 수 있다.

단점

  • 복잡한 문법을 표현하려면 Expression과 Parser가 복잡해진다.

Example

정규표현식

Pattern.matches("[a-z]{6}", "spring");

Expression language - SPEL
레퍼런스 참고하기

Book book = new Book("spring");
 
SMALL

'강의 > Design pattern' 카테고리의 다른 글

중재자(Mediator) 패턴  (0) 2022.09.22
이터레이터(Iterator) 패턴  (0) 2022.09.22
커맨드(Command) 패턴  (0) 2022.09.22
책임 연쇄 패턴  (0) 2022.09.22
프록시(Proxy) 패턴  (0) 2022.09.22