DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Using Interpreter Design Pattern In Java
  • The Future of Java and AI: Coding in 2025
  • Tired of Spring Overhead? Try Dropwizard for Your Next Java Microservice
  • Using Python Libraries in Java

Trending

  • How To Develop a Truly Performant Mobile Application in 2025: A Case for Android
  • Endpoint Security Controls: Designing a Secure Endpoint Architecture, Part 2
  • Agile and Quality Engineering: A Holistic Perspective
  • Why High-Performance AI/ML Is Essential in Modern Cybersecurity
  1. DZone
  2. Coding
  3. Java
  4. Interpreter Pattern Tutorial with Java Examples

Interpreter Pattern Tutorial with Java Examples

Learn the Interpreter Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered

By 
James Sugrue user avatar
James Sugrue
DZone Core CORE ·
May. 11, 10 · Tutorial
Likes (0)
Comment
Save
Tweet
Share
54.0K Views

Join the DZone community and get the full member experience.

Join For Free

Today's pattern is the Interpreter pattern, which defines a grammatical representation for a language and provides an interpreter to deal with this grammar.

Interpreter in the Real World 

The first example of interpreter that comes to mind, is a translator, allowing people to understand a foreign language. Perhaps musicians are a better example: musical notation is our grammar here, with musicians acting as interpreters, playing the music.

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone's Design Patterns Refcard is the best place to start. 

The Interpreter Pattern

The Interpreter pattern is known as abehavioural pattern, as it's used to manage algorithms, relationships and responsibilities between objects.. Thedefinition of Interpreter as provided in the original Gang of Four book on DesignPatterns states: 

Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.

The following diagram shows how the interpreter pattern is modelled.


Context contains information that is global to the interpreter. The AbstractExpression provides an interface for executing an operation. TerminalExpression implements the interpret interface associated with any terminal expressions in the defined grammar. 

The Client either builds the Abstract Syntax Tree, or the AST is passed through to the client. An AST is composed of both TerminalExpressions and NonTerminalExpressions. The client will kick off the interpret operation. Note that the syntax tree is usually implemented using the Composite pattern

The pattern allows you to decouple the underlying expressions from the grammar. 

When Would I Use This Pattern?

The Interpreter pattern should be used when you have a simple grammar that can be represented as an Abstract Syntax Tree. This is the more obvious use of the pattern. A more interesting and useful application of Interpreter is when you need a program to produce different types of output, such as a report generator. 

So How Does It Work In Java?

I'll use a simple example to illustrate this pattern. We're going to create our own DSL for searching Amazon. To do this, we'll need to have a context that uses an Amazon web service to run our queries.

//Context public class InterpreterContext{//assume web service is setupprivate AmazonWebService webService;   public InterpreterContext(String endpoint){//create the web service.}   public ArrayList<Movie> getAllMovies(){   return webService.getAllMovies();}public ArrayList<Book> getAllBooks(){  return webService.getAllBooks();}}

Next, we'll need to create an abstract expression: 

//Abstract Expression public abstract class AbstractExpression{   public abstract String interpret( InterpreterContext context);}

We'll have many different expressions to interpret our queries. For illustration,let's create just one: 

//Concrete Expression public class BookAuthorExpression extends AbstractExpression{private String searchString;   public BookAuthorExpression(String searchString)   {this.searchString = searchString;   }   public String interpret(InterpreterContext context)   {ArrayList<Book> books = context.getAllBooks();StringBuffer result = new StringBuffer();for(Book book: books){ if(book.getAuthor().equalsIgnoreCase(searchString)) {result.append(book.toString()); }}return result;   }}

Finally, we need a client to drive all of this. Let's assume that our language is of the following type of syntax: 

books by author 'author name'

The client will determine which expression to use to get our results: 

//client public class AmazonClient {  private InterpreterContext context;  public AmazonClient(InterpreterContext context) {this.context = context; }  /**  * Interprets a string input of the form   *   movies | books by title | year | name '<string>'  */ public String interpret(String expression) {//we need to parse the string to determine which expression to use AbstractExpression exp = null; String[] stringParts = expression.split(" ");String main = stringParts[0];String sub = stringParts[2];//get the query partString query = expression.substring(expression.firstIndexOf("'"), expression.lastIndexOf("'"));if(main.equals("books")){if(sub.equals("title"){  exp = new BookTitleExpression(query);}if(sub.equals("year"){   exp = new BookYearExpression(query);}}else  if(main.equals("movie"))  {//similar statements to create movie expressions  }    if(exp != null){exp.interpret(context);} }   public static void main(String[] args)  {InterpreterContext context  = new InterpreterContext("http://aws.amazon.com/");AmazonClient client = new AmazonClient();//run a queryString result = client.interpret("books by author 'John Connolly'");System.out.println(result); }}

I admit the example is a bit simple, and you would probably have a more intelligent context, but that should give you the idea of how this pattern works.

Watch Out for the Downsides

Efficiency is a big concern for any implementation of this pattern. Introducing your own grammar requires extensive error checking, which will be time consuming for the programmer to implement, and needs careful design in order to run efficiently at runtime. Also, as the grammar becomes more complicated, the maintainence effort is increased. 

Next Up

As we've mentioned the Composite pattern in this article when dealing with Abstract Syntax Trees, I'll cover Composite in the next article.

Enjoy the Whole "Design Patterns Uncovered" Series:

Creational Patterns

  • Learn The Abstract Factory Pattern
  • Learn The Builder Pattern
  • Learn The Factory Method Pattern
  • Learn The Prototype Pattern

Structural Patterns

  • Learn The Adapter Pattern
  • Learn The Bridge Pattern
  • Learn The Decorator Pattern
  • Learn The Facade Pattern
  • Learn The Proxy Pattern

Behavioral Patterns

  • Learn The Chain of Responsibility Pattern
  • Learn The Command Pattern
  • Learn The Interpreter Pattern
  • Learn The Iterator Pattern
  • Learn The Mediator Pattern
  • Learn The Memento Pattern
  • Learn The Observer Pattern
  • Learn The State Pattern
  • Learn The Strategy Pattern
  • Learn The Template Method Pattern
  • Learn The Visitor Pattern


Interpreter pattern Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Using Interpreter Design Pattern In Java
  • The Future of Java and AI: Coding in 2025
  • Tired of Spring Overhead? Try Dropwizard for Your Next Java Microservice
  • Using Python Libraries in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!