Interpreter Design Pattern

What is Interpreter Design Pattern?

  • It falls under behavioral design pattern.
  • It provides a way to evaluate language grammar or expression.
  • It is useful for developing domain-specific languages or notations.
  • It defines the ability to set a language’s grammar.
  • Java compiler that interprets Java source code into byte-code.
  • Defines a grammatical representation for a language and an interpreter to interpret the grammar.
  • It is widely used in compilers that are implemented with Object Oriented languages.

Real Life Examples of Interpreter Design Pattern

translate photoLet's consider Google translator; it will translate from any language to any language. Here, Google translator is acting as an interpreter which translates from one language (English) to another language (Tamil) on behalf of us. It follows the language rules which means Grammar for translating.

Example 2:

Let’s consider programming languages like C, C++, Java, etc. Here, the interpreter design pattern has been used. 

Could you guess?

Let’s narrow down our example to Java programming language. We write Java programs which are the source files. Java compiler converts the source code to byte code by following the set of grammar rules. Here, the compiler has been implemented using Interpreter Design Pattern. Most of the compilers are designed and implemented using a set of grammar rules 

UML Class Diagram of Interpreter Design Pattern

Interpreter Design Pattern Java Implementation

Step 1:

public class Voltage
{

    private int voltage;

    public Voltage(int v)
    {
        this.voltage = v;
    }

    public int getVolts()
    {
        return voltage;
    }

    public void setVolts(int voltage)
    {
        this.voltage = voltage;
    }

}

Tutorial Videos of Interpreter Design Pattern

For tutorial videos, please check out the premium Software Design Pattern course on Udemy.  

Share