如何用java解释器模式翻译句子

时间:2018-04-06 14:55:10

标签: java

我现在正试图在java中创建一个将句子翻译成不同表示的程序。我想用解释器模式做到这一点。该程序接收荷兰语的句子作为输入,并可以将该句子翻译成各种表示。表示的一个例子是英语中的相同句子。但我不知道从哪里开始。任何人都可以帮助我或给我提示从哪里开始?

这是我的代码。 Main.java

public class Main {
    static Expression buildInterpreterTree() {
        Expression terminal1 = new TerminalExpression("John");
        Expression terminal2 = new TerminalExpression("Henry");
        Expression terminal3 = new TerminalExpression("Mary");
        Expression terminal4 = new TerminalExpression("Owen");
        Expression alternation1 = new OrExpression(terminal2, terminal3); 
        Expression alternation2 = new OrExpression(terminal1, alternation1);
        return new AndExpression(terminal4, alternation2);
    }

    public static void main(String[] args) {
        String context = "Mary Owen";
        Expression define = buildInterpreterTree();
        System.out.println(context + " is " + define.interpret(context));
    }
}

Expression.java

public abstract class Expression {
    abstract public boolean interpret(String str); 
}

TerminalExpression.java

public class TerminalExpression extends Expression {
    private String literal = null;

    public TerminalExpression(String str) { 
        literal = str; 
    }

    public boolean interpret(String str) { 
        StringTokenizer st = new StringTokenizer(str);
        while (st.hasMoreTokens()) { 
            String test = st.nextToken();
            if (test.equals(literal)) {
                return true;
            }
        }
        return false;
    }

}

OrExpression.java

public class OrExpression extends Expression {
    private Expression expression1 = null;
    private Expression expression2 = null;

    public OrExpression(Expression expression1, Expression expression2) { 
        this.expression1 = expression1;
        this.expression2 = expression2; 
    }

    public boolean interpret(String str) { 
        return expression1.interpret(str) || expression2.interpret(str);
    } 
}

AndExpression

public class AndExpression extends Expression {
    private Expression expression1 = null;
    private Expression expression2 = null;

    public AndExpression(Expression expression1, Expression expression2) { 
        this.expression1 = expression1;
        this.expression2 = expression2;
    }

    public boolean interpret(String str) { 
        return expression1.interpret(str) && expression2.interpret(str);
    } 
}

0 个答案:

没有答案