Behavioral Patterns  «Prev 

Interpreter Pattern in Java

Interpreter Pattern Diagram
In order to implement the Interpreter Pattern, we need to
  1. create the Interpreter context engine that will do the interpretation work.
  2. create different Expression implementations that will consume the functionalities provided by the Interpreter Context.
  3. create the client that will take the input from user and decide which Expression to use and then generate output for the user.

InterpreterContext

package com.java.behavioral.interpreter; 
public class InterpreterContext {
 public String getBinaryFormat(int i){
  return Integer.toBinaryString(i);
 }
 public String getHexadecimalFormat(int i){
  return Integer.toHexString(i);
 }
}

Now we need to create different types of Expressions that will consume the interpreter context class.
package com.java.behavioral.interpreter;
 
public interface Expression {
 String interpret(InterpreterContext ic);
}

We will have two Expression implementations,
  1. one to convert int to binary and
  2. the other to convert int to hexadecimal format.

package com.java.behavioral.interpreter;
public class IntToBinaryExpression implements Expression {
 private int i;
 public IntToBinaryExpression(int c){
  this.i=c;
 }
 @Override
 public String interpret(InterpreterContext ic) {
  return ic.getBinaryFormat(this.i);
 }
}

package com.java.behavioral.interpreter;
public class IntToHexExpression implements Expression {
 private int i;
 public IntToHexExpression(int c){
  this.i=c;
 }
 @Override
 public String interpret(InterpreterContext ic) {
  return ic.getHexadecimalFormat(i);
 }
}

Create the client application that will have the logic to parse the user input and pass it to the correct expression and then use the output to generate the user response.

package com.java.behavioral.interpreter;
public class InterpreterClient {
 public InterpreterContext ic;
 public InterpreterClient(InterpreterContext i){
  this.ic=i;
 }
 public String interpret(String str){
  Expression exp=null;
  //create rules for expressions
  if(str.contains("Hexadecimal")){
   exp=new IntToHexExpression(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(ic);
 }
 public static void main(String args[]){
  String str1 = "17 in Binary";
  String str2 = "17 in Hexadecimal";
  InterpreterClient ec = new InterpreterClient(new InterpreterContext());
  System.out.println(str1+"= "+ec.interpret(str1));
  System.out.println(str2+"= "+ec.interpret(str2));
 }
}
The client also has a main method for testing purpose, when we run above we get following output:
17 in Binary= 10001
17 in Hexadecimal= 11