Definition
Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
UML class diagram
Participants
The classes and/or objects participating in this pattern are:
- AbstractExpression - declares an interface for executing an operation
- TerminalExpression
an instance is required for every terminal symbol in the sentence.
- NonterminalExpression
maintains instance variables of type AbstractExpression for each of the symbols R1 through Rn.
implements an Interpret operation for nonterminal symbols in the grammar. Interpret typically calls itself recursively on the variables representing R1 through Rn.
- Context - contains information that is global to the interpreter
- Client - builds (or is given) an abstract syntax tree representing a particular sentence in the language that the grammar defines. The abstract syntax tree is assembled from instances of the NonterminalExpression and TerminalExpression classes invokes the Interpret operation
Sample code in C#
///
/// MainApp startup class for Structural
/// Interpreter Design Pattern.
///
class MainApp
{
///
/// Entry point into console application.
///
static void Main()
{
Context context = new Context();
// Usually a tree
ArrayList list = new ArrayList();
// Populate 'abstract syntax tree'
list.Add(new TerminalExpression());
list.Add(new NonterminalExpression());
list.Add(new TerminalExpression());
list.Add(new TerminalExpression());
// Interpret
foreach (AbstractExpression exp in list)
{
exp.Interpret(context);
}
// Wait for user
Console.ReadKey();
}
}
///
/// The 'Context' class
///
class Context
{
}
///
/// The 'AbstractExpression' abstract class
///
abstract class AbstractExpression
{
public abstract void Interpret(Context context);
}
///
/// The 'TerminalExpression' class
///
class TerminalExpression : AbstractExpression
{
public override void Interpret(Context context)
{
Console.WriteLine("Called Terminal.Interpret()");
}
}
///
/// The 'NonterminalExpression' class
///
class NonterminalExpression : AbstractExpression
{
public override void Interpret(Context context)
{
Console.WriteLine("Called Nonterminal.Interpret()");
}
}
-
-
पुस्तकें(959)
-
कहते हैं: