Interpreter Design Pattern Tutorial

Interpreter Design Pattern TutorialWelcome to my Interpreter Design Pattern Tutorial! The Interpreter design pattern is ignored by most, but in this tutorial I’ll show you how to do some cool things with it.

In top of that, I’ll also answer all of the recent questions I’ve received about both Java Reflection and String manipulation. I found you can do pretty great things if you combine reflection with the interpreter design pattern.

All of the code follows the video and it is heavily commented to help you learn.

If you found this tutorial useful, it helps others when you tell Google

If you know someone who’d be interested in this crazy tutorial, feel free to share it

Code from the Video

CONVERSIONCONTEXT.JAVA

public class ConversionContext {

    private String conversionQues = "";
    private String conversionResponse = "";
    private String fromConversion = "";
    private String toConversion = "";
    private double quantity;
    
    String[] partsOfQues;

    public ConversionContext(String input)
    {
      this.conversionQues = input;
      
      partsOfQues = getInput().split(" ");
      
      fromConversion = getCapitalized(partsOfQues[1]);
      
      toConversion = getLowercase(partsOfQues[3]);
      
      quantity = Double.valueOf(partsOfQues[0]);
      
      conversionResponse = partsOfQues[0] + " "+ partsOfQues[1] + " equals ";
    }

    public String getInput() { return conversionQues; }
    
    public String getFromConversion() { return fromConversion; }
    
    public String getToConversion() { return toConversion; }
    
    public String getResponse() { return conversionResponse; }
    
    public double getQuantity() { return quantity; }
    
    // Make String lowercase
    
    public String getLowercase(String wordToLowercase){
    	
    	return wordToLowercase.toLowerCase();
    	
    }
    
    // Capitalizes the first letter of a word
    
    public String getCapitalized(String wordToCapitalize){
    	
    	// Make characters lower case
    	
    	wordToCapitalize = wordToCapitalize.toLowerCase();
    	
    	// Make the first character uppercase
    	
    	wordToCapitalize = Character.toUpperCase(wordToCapitalize.charAt(0)) + wordToCapitalize.substring(1);
    	
    	// Put s on the end if not there
    	
    	int lengthOfWord = wordToCapitalize.length();
    	
    	if((wordToCapitalize.charAt(lengthOfWord -1)) != 's'){
    		
    		wordToCapitalize = new StringBuffer(wordToCapitalize).insert(lengthOfWord, "s").toString();
    		
    	}
    	
    	return wordToCapitalize;
    	
    }

}

EXPRESSION.JAVA

public abstract class Expression {
	
	public abstract String gallons(double quantity);
	public abstract String quarts(double quantity);
	public abstract String pints(double quantity);
	public abstract String cups(double quantity);
	public abstract String tablespoons(double quantity);
	
}

GALLONS.JAVA

public class Gallons extends Expression{

	public String gallons(double quantity) {
		
		return Double.toString(quantity);
	}

	public String quarts(double quantity) {
		return Double.toString(quantity*4);
	}

	public String pints(double quantity) {
		return Double.toString(quantity*8);
	}

	public String cups(double quantity) {
		return Double.toString(quantity*16);
	}

	public String tablespoons(double quantity) {
		return Double.toString(quantity*256);
	}
	
}

QUARTS.JAVA

public class Quarts extends Expression{

	public String gallons(double quantity) {
		
		return Double.toString(quantity/4);
	}

	public String quarts(double quantity) {
		return Double.toString(quantity);
	}

	public String pints(double quantity) {
		return Double.toString(quantity*2);
	}

	public String cups(double quantity) {
		return Double.toString(quantity*4);
	}

	public String tablespoons(double quantity) {
		return Double.toString(quantity*64);
	}
	
}

PINTS.JAVA

public class Pints extends Expression{

	public String gallons(double quantity) {
		
		return Double.toString(quantity/8);
	}

	public String quarts(double quantity) {
		return Double.toString(quantity/2);
	}

	public String pints(double quantity) {
		return Double.toString(quantity);
	}

	public String cups(double quantity) {
		return Double.toString(quantity*2);
	}

	public String tablespoons(double quantity) {
		return Double.toString(quantity*32);
	}
	
}

CUPS.JAVA

public class Cups extends Expression{

	public String gallons(double quantity) {
		
		return Double.toString(quantity/16);
	}

	public String quarts(double quantity) {
		return Double.toString(quantity/4);
	}

	public String pints(double quantity) {
		return Double.toString(quantity/2);
	}

	public String cups(double quantity) {
		return Double.toString(quantity);
	}

	public String tablespoons(double quantity) {
		return Double.toString(quantity*16);
	}
	
}

TABLESPOONS.JAVA

public class Tablespoons extends Expression{

	public String gallons(double quantity) {
		
		return Double.toString(quantity/256);
	}

	public String quarts(double quantity) {
		return Double.toString(quantity/64);
	}

	public String pints(double quantity) {
		return Double.toString(quantity/32);
	}

	public String cups(double quantity) {
		return Double.toString(quantity/16);
	}

	public String tablespoons(double quantity) {
		return Double.toString(quantity);
	}
	
}

MEASUREMENTCONVERSION.JAVA

import java.lang.reflect.*;

import javax.swing.*;

public class MeasurementConversion {
	
	public static void main(String[] args){
		
		// Create pop up window that asks for a question
		
		JFrame frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		String questionAsked = JOptionPane.showInputDialog(frame, "What is your question");
		
		// Add the question to the context for analysis
		
		ConversionContext question = new ConversionContext(questionAsked);
		
		String fromConversion = question.getFromConversion();
		
		String toConversion = question.getToConversion();
		
		double quantity = question.getQuantity();
		
		try {
			
			// Get class based on the from conversion string
			
			Class tempClass = Class.forName(fromConversion);
			
			// Get the constructor dynamically for the conversion string
			
			Constructor con = tempClass.getConstructor();
			
			// Create a new instance of the object you want to convert from
			
			Object convertFrom = (Expression) con.newInstance();
			
			// Define the method parameters expected by the method that
			// will convert to your chosen unit of measure
			
			Class[] methodParams = new Class[]{Double.TYPE};
			
			// Get the method dynamically that will be needed to convert
			// into your chosen unit of measure

			Method conversionMethod = tempClass.getMethod(toConversion, methodParams);
			
			// Define the method parameters that will be passed to the above method
			
			Object[] params = new Object[]{new Double(quantity)};
			
			// Get the quantity after the conversion
			
			String toQuantity = (String) conversionMethod.invoke(convertFrom, params);
			
			// Print the results
			
			String answerToQues = question.getResponse() + 
					toQuantity + " " + toConversion;
			
			JOptionPane.showMessageDialog(null,answerToQues);
			
			// Closes the frame after OK is clicked
			
			frame.dispose();
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
}

13 Responses to “Interpreter Design Pattern Tutorial”

  1. mr.roshik says:

    youtube is still off from Bangladesh. may be after few days we will be able to access. i dont know any alternative site of youtube.

    • admin says:

      It looks like it may be off for a long time? From what I read, Google is saying they won’t block free speech of any kind even if it could be inflammatory. The government in Bangladesh is demanding that they remove anything that could be deemed anti-religious.

      I would never make any judgements on any other country because I have no knowledge of any country but the U.S. What I can tell you about the U.S. though is that our only freedom is the freedom of speech. Actually freedom of speech is under attack as you can see from the Wikileak attack that is going on.

      I haven’t seen this video that has upset so many people and I don’t plan on watching it. I just think it is sad that a few lone lunatics (video makers) are able to so easily bend governments. There isn’t much that makes sense to me though government wise?

  2. boris says:

    great tutorials!

  3. Sam says:

    Bangladesh should merge with india, and be a free country, where you have all the rights as a citizen.

  4. Sam says:

    Derek
    First i want to thank you for the best vidoes of design pattern on youtube.
    I copied all the code, and when i run, it gives me this error pasted below

    java.lang.ClassNotFoundException: Gallons
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at com.MeasurementConversion.main(MeasurementConversion.java:33)

  5. Langston says:

    Hi Derek,

    Thank you very much for such great tutorial, I want to know are there any other scenarios we could make user of interpreter design patter?

    Best Regards,

    Langston

    • Derek Banas says:

      Hi Langston,

      You’re very welcome 🙂 You could use the Interpreter any time you need to translate from one thing to another. Languages, from a note to a sound, etc. You could also use it to generate different reports based off of different data presented. It is a great pattern.

      I hope that helps
      Derek

  6. Umair says:

    Hi Derek,

    I had an assignment for simulation of robot in mars planet. I was able to do this using your java game spaceship tutorials.

    Thank you very much,some how i feel like the code is to be dedicated to you.

    In this video you have mentioned some game tutorial called Zorak game. Do you mind publishing the code.

    Thank you once again

    • Derek Banas says:

      Hi Umair,

      I’m very happy that I was able to help. That game was a lot of fun to make. I plan on making a ton of games over the course of 2014. I’m not sure what I did with the Zork code, but I’ll cover how to make a game like that soon.

Leave a Reply

Your email address will not be published.

Google+