Interpreter Design Pattern

Introduction:
Sometimes you want to define a grammar for special language for certain reasons. After defining the syntax of this language, you need to build an interpreter to interpret the language and do actions accordingly. Interpreter Design Pattern help you to define a well structure object oriented classed to parse your expressions against the new language you defined
Example:

InterpreterDesignPattern

 

static void Main(string[] args)
{
string hxNumber = Console.ReadLine(); // Hexadecimal number
Context context = new Context(hxNumber);
HexadecimalNumber hex = new HexadecimalNumber();
hex.Interpret(context);
Console.WriteLine(“{0} HexaDecimal Numbering System = {1} Decimal Numbering System” ,hxNumber, context.Output);
// Wait for user
Console.ReadKey();
}
class HexadecimalNumber :Expression
{
public override string Symbol10()
{
return “A”;
}
public override string Symbol11()
{
return “B”;
}
public override string Symbol12()
{
return “C”;
}
public override string Symbol13()
{
return “D”;
}
public override string Symbol14()
{
return “E”;
}
public override string Symbol15()
{
return “F”;
}
public override bool IsSymbolNumberBetween0To9(string num)
{
int tmpNum;
return int.TryParse(num,out tmpNum);
}
public override int Multiplier()
{
return 16;
}
}
abstract class Expression
{
public void Interpret(Context context)
{
if (context.Input.Length == 0)
return;
int value = 0;
if (context.Input.StartsWith(Symbol10()))
{
value = 10;
}
else if (context.Input.StartsWith(Symbol11()))
{
value = 11;
}
else if (context.Input.StartsWith(Symbol12()))
{
value = 12;
}
else if (context.Input.StartsWith(Symbol13()))
{
value = 13;
}
else if (context.Input.StartsWith(Symbol14()))
{
value = 14;
}
else if (context.Input.StartsWith(Symbol15()))
{
value = 15;
}
else if (IsSymbolNumberBetween0To9(context.Input.Substring(0, 1)))
{
value = int.Parse(context.Input.Substring(0, 1));
}
else
{
Console.WriteLine(“Invalid Hexadecimal Number!”);
context.Output = 0;
return;
}
context.Input = context.Input.Substring(1);
context.Output += (int)(value * Math.Pow(Multiplier() , context.Input.Length ));
Interpret(context);
}
public abstract string Symbol10();
public abstract string Symbol11();
public abstract string Symbol12();
public abstract string Symbol13();
public abstract string Symbol14();
public abstract string Symbol15();
public abstract bool IsSymbolNumberBetween0To9(string num);
public abstract int Multiplier();
}
class Context
{
private string inputValue;
private int outputValue;
// Constructor
public Context(string input)
{
this.inputValue = input;
}
// Gets or sets input
public string Input
{
get { return inputValue; }
set { inputValue = value; }
}
// Gets or sets output
public int Output
{
get { return outputValue; }
set { outputValue = value; }
}
}

Download Code