Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Interpreter Design Pattern
//Context class
public class Context
{
public int Input { get; set; }
public Context(int inputValue)
{
Input = inputValue;
}
}
//Expression Interface
public interface IExpression
{
void Interpret(Context context);
}
class Program
{
static void Main(string[] args)
{
Context ctx = new Context(5642);
IExpression exp1 = new WordExpression();
exp1.Interpret(ctx);
Context ctx1 = new Context(397);
SubExpression subExp = new SubExpression();
subExp.Expression1 = new WordExpression();
subExp.Interpret(ctx1);
Console.ReadLine();
}
}
//Non-terminal expression class
public class SubExpression : IExpression
{
public IExpression Expression1 { get; set; }
public void Interpret(Context context)
{
Console.WriteLine("Running Sub Expression 1");
Expression1.Interpret(context);
}
}
//Terminal expression class
public class WordExpression : IExpression
{
public Dictionary<int, string> numberWord = new Dictionary<int, string>() {
{ 1, "One" }, { 2, "Two" }, { 3, "Three" }, { 4, "Four" }, { 5, "Five" },
{ 6, "Six" }, { 7, "Seven" }, { 8, "Eight" }, { 9, "Nine" }, { 0, "Zero" } };
public void Interpret(Context context)
{
Console.Write("Input Value {0} - ", context.Input);
string value = context.Input.ToString();
if (value.Length > 0)
{
foreach (char chr in value)
{
int number = (int)Char.GetNumericValue(chr);
Console.Write("{0} ", numberWord[number]);
}
Console.WriteLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment