Java Design Pattern: Interpreter

Major revision in progress ... Please come back later.

Interpreter pattern is used when some context needs to be interpreted. The following example is a very simple Interpreter implementation. It interpretes letter "a" and "b" to "1" and "2".

Class Diagram

interpreter pattern class diagram

Note that: the dependency is also shown in diagram to make the structure more understandable.

Java Code

 
class Context { 
 
    private String input; 
    private String output; 
 
    public Context(String input) { 
        this.input = input; 
        this.output = "";
    } 
 
    public String getInput() { 
        return input; 
    } 
    public void setInput(String input) { 
        this.input = input; 
    } 
    public String getOutput() { 
        return output; 
    } 
    public void setOutput(String output) { 
        this.output = output; 
    } 
}
 
abstract class Expression {    
    public abstract void interpret(Context context); 
}
 
class AExpression extends Expression { 
    public void interpret(Context context) { 
        System.out.println("a expression"); 
        String input = context.getInput(); 
 
        context.setInput(input.substring(1)); 
        context.setOutput(context.getOutput()+ "1"); 
    } 
 
}
 
class BExpression extends Expression { 
    public void interpret(Context context) { 
        System.out.println("b expression"); 
        String input = context.getInput(); 
 
        context.setInput(input.substring(1)); 
        context.setOutput(context.getOutput()+ "2"); 
    } 
}
 
public class TestInterpreter {
	 public static void main(String[] args) { 
	        String str = "ab"; 
	        Context context = new Context(str); 
 
	        List<Expression> list = new ArrayList<Expression>(); 
	        list.add(new AExpression()); 
	        list.add(new BExpression()); 
 
	        for(Expression ex : list) { 
	            ex.interpret(context); 
 
	        } 
 
	        System.out.println(context.getOutput()); 
	    } 
}

Interpreter pattern used in JDK

java.util.Pattern

Category >> Design Patterns Stories  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • test

    i think it’s strategy pattern .

  • 原理和拦截器模式很想,两者区别在什么地方呢,还有就是解释器模式能解决哪种业务方面的问题!

  • Nikolay Pasko

    Context adds complexity that beats the complexity of Interpreter itself.
    Pehaps you should reconsider it.
    I’d recomment to dump the Context class completely, as it serves no purpose but to keep a two-character string.

    Additionally, the example does not show how expressionA interprets “a” as “1”, it just interprets “whatever symbol is now first in the context input” to “1”.
    expressionB does the same, interpreting anything to “2”.