Monday, June 4, 2012

Behavioral Patterns - 3.Interpreter Pattern

In our day to day coding and development activities, situations may arise where we may need to evaluate/process a sentence or a group of strings in different ways.

A natural language parser could be an example for the above scenario. Such problems, can be handled with the help of Interpreter Pattern.

Generally, we define a Context which contains the sentence that needs to be interpreted. Then we define some interpreters to operate over the context and updates the context with the interpreted result.

There will be an abstraction over the interpreters.Seperate implementations can be written for their own interpretation needs.

For example, we are going to design some encryption algorithms. First of all, we need to define a Context, which contains the string or sentence that needs to be encrypted.

After that, we define an abstraction for the encryption algorithm. Then we define separate implementations for the algorithm that will work over the context and updates it with the encrypted string.

Being built with the Interpreter pattern,it will be a very simple task to change or add an algorithm to the stack with very minimal changes to the code.

Following diagram explains the Interpreter pattern,



Code snippet

Client:

  Context context=new Context(name); //Define the Context
  Cryptography cryptography=new MyCryptography();
  cryptography.interpret(context); 
//Invoke the Interpreter over the context
 
  cryptography=new CustomCryptography(); //Changing algorithm
  cryptography.interpret(context);


Interpretor(Abstraction):

abstract class Cryptography{
 public abstract void interpret(Context context);
//Interpreter method
}


Implementation(Cryptography Algorithm):

 @Override
 public void interpret(Context context) { 
//Interpreter Implementation
  char names[]=context.getName().toCharArray();
  int count=0;
  for(char name:names){
   names[count++]=(char)((int)name+2);
  }
  context.setResult(new String(names));
//Update the Context with result
 }

No comments:

Post a Comment