-
행위패턴 : Interpreter 패턴디자인패턴 2013. 2. 27. 10:11
분류 : 행위패턴(Behavioral Patterns)
정의 :
언어에서 문장을 해석할때 사용되는 패턴
용도 :
- SQL 같은 데이터베이스 쿼리 언어에 상용
- 통신 프로토콜을 설명하는데 자주사용됨.
소스
import java.util.Map; public interface Expression { public int interpret (Map
variables); } import java.util.Map; public class Minus implements Expression { Expression leftOperand; Expression rightOperand; public Minus(Expression left, Expression right) { leftOperand = left; rightOperand = right; } public int interpret(Map variables) { return leftOperand.interpret(variables) - rightOperand.interpret(variables); } } import java.util.Map; public class Number implements Expression { private int number; public Number(int number) { this.number = number; } public int interpret(Map variables) { return number; } } import java.util.Map; public class Plus implements Expression { Expression leftOperand; Expression rightOperand; public Plus(Expression left, Expression right) { leftOperand = left; rightOperand = right; } public int interpret(Map variables) { return leftOperand.interpret(variables) + rightOperand.interpret(variables); } } import java.util.Map; public class Variable implements Expression { private String name; public Variable(String name) { this.name = name; } public int interpret(Map variables) { if(null==variables.get(name)) return 0; //Either return new Number(0). return variables.get(name).interpret(variables); } } import java.util.Map; import java.util.Stack; public class Evaluator implements Expression { private Expression syntaxTree; public Evaluator(String expression) { Stack expressionStack = new Stack (); for (String token : expression.split(" ")) { if (token.equals("+")) { Expression subExpression = new Plus(expressionStack.pop(), expressionStack.pop()); expressionStack.push( subExpression ); } else if (token.equals("-")) { // it's necessary remove first the right operand from the stack Expression right = expressionStack.pop(); // ..and after the left one Expression left = expressionStack.pop(); Expression subExpression = new Minus(left, right); expressionStack.push( subExpression ); } else expressionStack.push( new Variable(token) ); } syntaxTree = expressionStack.pop(); } public int interpret(Map context) { return syntaxTree.interpret(context); } } import java.util.Map; import java.util.HashMap; public class InterpreterExample { public static void main(String[] args) { String expression = "w x z - +"; Evaluator sentence = new Evaluator(expression); Map variables = new HashMap (); variables.put("w", new Number(5)); variables.put("x", new Number(10)); variables.put("z", new Number(42)); int result = sentence.interpret(variables); System.out.println(result); } } 참고자료
'디자인패턴' 카테고리의 다른 글
행위패턴 : Mediator 패턴 (0) 2013.02.28 행위패턴 : Iterator 패턴 (0) 2013.02.27 행위패턴 : Command 패턴 (0) 2013.02.26 행위패턴 : Chain of Responsibility 패턴 (0) 2013.02.07 구조패턴 : Proxy 패턴 (0) 2013.02.06 댓글