Skip to content

Instantly share code, notes, and snippets.

@miteshsureja
Created May 10, 2017 14:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miteshsureja/6cc86c51ae3eb75f7ad75aa5246f7a95 to your computer and use it in GitHub Desktop.
Save miteshsureja/6cc86c51ae3eb75f7ad75aa5246f7a95 to your computer and use it in GitHub Desktop.
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();
}
}
}
@miteshsureja
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment