Java interpreter design pattern

Dictionary meaning of interpreter: A person who interprets, especially one who translates speech orally or into sign language.

Java interpreter design pattern comes under behavioural design patterns. It is used to provide a way to evaluate language grammar and provides an interpreter to deal with this grammar.

Java compiler is one of the example of interpreter design pattern.

Example

Interpreter.java

package com.w3spoint;
 
public class Interpreter {
	public String getBinaryFormat(int i){
		return Integer.toBinaryString(i);
	}
 
	public String getOctalFormat(int i){
		return Integer.toOctalString(i);
	}
}

Expression.java

package com.w3spoint;
 
public interface Expression {
	String interpret(Interpreter interpreter);
}

IntToBinaryExpression.java

package com.w3spoint;
 
public class IntToBinaryExpression implements Expression {
	private int num;
 
	public IntToBinaryExpression(int num){
		this.num=num;
	}
 
	@Override
	public String interpret(Interpreter interpreter) {
		return interpreter.getBinaryFormat(this.num);
	}		
}

IntToOctalExpression.java

package com.w3spoint;
 
public class IntToOctalExpression implements Expression {
	private int num;
 
	public IntToOctalExpression(int num){
		this.num=num;
	}
 
	@Override
	public String interpret(Interpreter interpreter) {
		return interpreter.getOctalFormat(this.num);
	}		
}

InterpreterPatternTest.java

package com.w3spoint;
 
public class InterpreterPatternTest {
	public Interpreter interpreter;
 
	public InterpreterPatternTest(Interpreter i){
		this.interpreter=i;
	}
 
	public String interpret(String str){
		Expression exp = null;
		if(str.contains("Octal")){
			exp=new IntToOctalExpression(Integer.parseInt(str.substring(0,str.indexOf(" "))));
		}else if(str.contains("Binary")){
			exp=new IntToBinaryExpression(Integer.parseInt(str.substring(0,str.indexOf(" "))));
		}else return str;
 
		return exp.interpret(interpreter);
	}
	public static void main(String args[]){
		String str1 = "15 in Binary: ";
		String str2 = "15 in Octal: ";
 
		InterpreterPatternTest interpreterPatternTest = new InterpreterPatternTest(new Interpreter());
		System.out.println(str1+"= "+interpreterPatternTest.interpret(str1));
		System.out.println(str2+"= "+interpreterPatternTest.interpret(str2));
	}
}

Output

15 in Binary: = 1111
15 in Octal: = 17
Content Protection by DMCA.com
Please Share