디자인패턴 해석자 (Interpreter)

황제낙엽 2008.06.25 23:28 조회 수 : 1135 추천:93

sitelink3 http://1 
extra_vars4 ko 
extra_vars6 sitelink1 

Interpreter pattern

From Wikipedia, the free encyclopedia
Jump to: navigation, search

In computer programming, the interpreter pattern is a particular design pattern. The interpreter pattern specifies how to evaluate sentences in a language. The basic idea is to have a class for each symbol (terminal or nonterminal) in a specialized computer language. The syntax tree of a sentence in the language is an instance of the composite pattern and is used to evaluate (interpret) the sentence.[1]


?

Contents

[hide]

[edit] Uses for the Interpreter pattern

  • Specialized database query languages such as SQL.
  • Specialized computer languages which are often used to describe communication protocols.
  • Most general-purpose computer languages actually incorporate several specialized languages.

[edit] Structure

Interpreter_UML_class_diagram.jpg

[edit] Example


The following Reverse Polish notation example illustrates the interpreter pattern. The grammar
expression ::= plus | minus | variable | number
plus ::= expression expression '+'
minus ::= expression expression '-'
variable  ::= 'a' | 'b' | 'c' | ... | 'z'
digit = '0' | '1' | ... '9'
number ::= digit | digit number

defines a language which contains reverse polish expressions like:
a b +
a b c + -
a b + c a - -

Following the interpreter pattern there is a class for each grammar rule.

import java.util.HashMap;
 
interface Expression {
    public int interpret(HashMap<String,Expression> variables);
}
 
class Number implements Expression {
    private int number;
    public Number(int number)       { this.number = number; }
    public int interpret(HashMap<String,Expression> variables)  { return number; }
}
 
class Plus implements Expression {
    Expression leftOperand;
    Expression rightOperand;
    public Plus(Expression left, Expression right) { 
        leftOperand = left; 
        rightOperand = right;
    }
 
    public int interpret(HashMap<String,Expression> variables)  { 
        return leftOperand.interpret(variables) + rightOperand.interpret(variables);
    }
}
 
class Minus implements Expression {
    Expression leftOperand;
    Expression rightOperand;
    public Minus(Expression left, Expression right) { 
        leftOperand = left; 
        rightOperand = right;
    }
 
    public int interpret(HashMap<String,Expression> variables)  { 
        return leftOperand.interpret(variables) - rightOperand.interpret(variables);
    }
}
 
class Variable implements Expression {
    private String name;
    public Variable(String name)       { this.name = name; }
    public int interpret(HashMap<String,Expression> variables)  { 
        if(null==variables.get(name)) return 0; //Either return new Number(0).
        return variables.get(name).interpret(variables); 
    }
}

While the interpreter pattern does not address parsing[2] a parser is provided for completeness.

import java.util.HashMap;
import java.util.Stack;
 
class Evaluator implements Expression {
    private Expression syntaxTree;
 
    public Evaluator(String expression) {
        Stack<Expression> expressionStack = new Stack<Expression>();
        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(HashMap<String,Expression> context) {
        return syntaxTree.interpret(context);
    }
}

Finally evaluating the expression "w x z - +" with w = 5, x = 10, and z = 42.

import java.util.HashMap;
 
public class InterpreterExample {
    public static void main(String[] args) {
        String expression = "w x z - +";
        Evaluator sentence = new Evaluator(expression);
        HashMap<String,Expression> variables = new HashMap<String,Expression>();
        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);
    }
}


[edit] See also

[edit] References

  1. ^ Gamma, Erich; Richard Helm, Ralph Johnson, and John Vlissides (1995). Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley. pp. 243 ISBN 0-201-63361-2
  2. ^ Gamma, Erich; Richard Helm, Ralph Johnson, and John Vlissides (1995). Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley. pp. 247 ISBN 0-201-63361-2

[edit] External links

번호 제목 글쓴이 날짜 조회 수
64 [ChatGPT] 소프트웨어 품질 관리에서 필요로 하는 소양 황제낙엽 2025.05.02 242
63 [Selenium] 크롬 브라우저 실행 화면을 출력하거나 감추는 방법 황제낙엽 2024.05.05 377
62 [Selenium] 페이지 이동 함수 황제낙엽 2024.05.05 346
61 [Selenium] Chrome 실행 자동화 file 황제낙엽 2024.05.03 1498
60 [Selenium] MS Edge 실행 자동화(RPA, Robotic Process Automation) file 황제낙엽 2024.05.02 701
59 [Selenium] Warning : Unable to find CDP implementation matching 124 황제낙엽 2024.05.02 1062
58 프로젝트 WBS 예제 (Microsoft Project 2013) secret 황제낙엽 2021.05.12 0
57 WBS (Work Breakdown Structure) 황제낙엽 2020.06.18 286
56 프로젝트 진행 절차 file 황제낙엽 2020.05.21 405
55 BDD (Behaviour-Driven Development) 황제낙엽 2020.04.02 358
54 요구사항 개발과 요구사항 관리 요약(요구사항기술서 샘플) file 황제낙엽 2019.07.07 425
53 뒤늦게 정리하는 UML (Unified Modeling Language) 요약 file 황제낙엽 2017.03.29 767
52 StarUML™의 숨은 재미있는 기능 황제낙엽 2017.03.29 2481
51 The Facade Pattern file 황제낙엽 2017.01.04 655
50 와블스 프로세스(Warbles Process) 황제낙엽 2016.07.17 550
49 비 개발자 출신이 스크럼 마스터가 될 수 있는가? 황제낙엽 2015.06.25 621
48 디자인패턴[Observer 패턴] 황제낙엽 2013.10.18 500
47 PMBOK 5판 이해관계자 관리의 이해 [1] file 황제낙엽 2013.08.23 1650
46 Validation and Verification file 황제낙엽 2013.08.23 432
45 이해관계자의 관리/이해관계자 분석 황제낙엽 2013.08.23 670