Interpreter mode:
Interpreter: for a given language, define a representation of its syntax and define an interpreter which uses this interpreter to interpret sentences in the language.
Knowledge point:
String Matching, email identification, and phone number matching. Regular Expressions are an application of interpreter mode.
The interpreter mode is easy to change and expand.
The interpreter mode defines at least one class for each rule in the grammar, so the grammar containing many rules may be difficult to manage and maintain.
Demo1:
//An abstract expression that declares an abstract interpretation operation.
Abstract class abstractexpression
{
Public abstract void interpret (contextcontext );
}
// The Terminator expression, which can be used to explain the terminator in grammar.
// The interpret () method. Each terminator in grammar has a specific Terminator expression corresponding to it.
Class terminalexpression: abstractexpression
{
Public override void interpret (context)
{
Console. writeline ("terminal interpreter ");
}
}
// Non-terminator expression. A specific non-terminator expression class is required for every rule R1, R2. ..
Class nonterminalexpression: abstractexpression
{
Public override void interpret (context)
{
Console. writeline ("non-terminal interpreter ");
}
}
// Contains global information other than the interpreter
Class Context
{
Private string input;
Public String Input
{
Get {return input ;}
Set {input = value ;}
}
Private string output;
Public String output
{
Get {return output ;}
Set {output = value ;}
}
}
Static void Main (String [] ARGs)
{
Context context = new context ();
Ilist <shortactexpression> List = newlist <shortactexpression> ();
List. Add (New terminalexpression ());
List. Add (New nonterminalexpression ());
List. Add (New terminalexpression ());
List. Add (New terminalexpression ());
Foreach (effecactexpression exp in List)
{
Exp. interpret (context );
}
Console. readkey ();
}