Java Behavioral Design Patterns – Interpreter Design Pattern

The Interpreter design pattern is one of the behavioral design patterns that give specification about how to evaluate sentences in a language.

Java compiler or for that matter compiler for any language is the perfect example of this pattern. The user inputs are converted into a language that is understandable by underlying JVM. In this pattern, the problem is generally solved by:

  1. Defining grammar or rules for language
  2. The rules are interpreted and processed upon.

<Here are ALL other Java Design Patterns, explained in detail with examples>

Interpreter Design Pattern by Example

When implementing interpreter design pattern, we need to create an interpreter engine. This engine will do the interpretation for us. We also design different expression implementations. These concrete implementations will utilize the functionalities provided by interpreter engine.

Of course, we will also write a simple client that will take user input (in our case sample string of instructions) and process it with customized interpreter engine.

For our demo purpose, we will define an interpreter engine that will understand basic addition and subtraction instructions. The instructions will be in the form of humanly understandable syntax.

E.g. add 12 and 13 or subtract 76 from 621

Let’s define our simple Expression interface.

Interpreter Context 

As you can see our interpreter engine or context provides functionality to parse integers out of string and perform the requested operation on it.

Add Expression

Subtract Expression

You can see that our expression implementations are simply using the functionality provided by Interpreter Context.

Now let’s see how the actual client will send the input.

Output:

So we have developed our own Domain Specific Language with the help of interpreter pattern.

Advantages

  1. We can create more than one interpreter for the same output and create the object of interpreter based on the given input.
  2. It’s easy to change and expand the grammar. Existing expressions can be easily modified, and new expressions can be defined on old ones.

Disadvantages

  1. If the grammar for day to day activity or processing easy then interpreter design pattern works the best. For complex instructions, your interpreter could become unmanageable.

Conclusion

The article helps you understand the interpreter pattern with a simple example.

You can download the code from our GitHub repository:

Download from Git

 

<Here are ALL other Java Design Patterns, explained in detail with examples>

Add a Comment

Your email address will not be published. Required fields are marked *