In the GoF book, the Interpreter Pattern is described with the following UML diagram: The UML diagram implies that 'Abstract Expression' should be implemented as an Abstract Class. Why is this? And why could the 'Abstract Expression' not just be an Interface?
I'm trying to make a simple interpreter for a subset of the Reverse Polish Notation. Here is the BNF that I'm implementing:
expression ::= plus | minus | variable | number
plus ::= expression expression '+'
minus ::= expression expression '-'
variable ::= 'a' | 'b' | 'c' | ... | 'z'
digit = '0' | '1' | ... | '9'
number ::= digit | digit number
Here is a minimal code example, only implementing plus, minus and number, written in C#:
namespace RPNInterpreter {
class Context
{
public Stack s {get;}
public Context() {
s = new Stack();
}
}
abstract class Expression
{
public abstract void Interpret(Context context);
}
class Plus : Expression
{
private Expression a;
private Expression b;
public Plus(Expression a, Expression b){
this.a = a;
this.b = b;
}
public override void Interpret(Context context)
{
a.Interpret(context);
b.Interpret(context);
context.s.Push((int) context.s.Pop() + (int) context.s.Pop());
}
}
class Minus : Expression
{
private Expression a;
private Expression b;
public Minus(Expression a, Expression b){
this.a = a;
this.b = b;
}
public override void Interpret(Context context)
{
b.Interpret(context);
a.Interpret(context);
context.s.Push((int) context.s.Pop() - (int) context.s.Pop());
}
}
class Number : Expression
{
private int n;
public Number(int n){
this.n = n;
}
public override void Interpret(Context context)
{
context.s.Push(n);
}
}
}
Since the Expression class doesn't hold any implementation I would argue that it should be an interface since it just defines functionality. But is there an use case with the interpreter pattern, where we actually need functionality in the 'Abstract Expression', and therefor should use an Abstract Class?
Aucun commentaire:
Enregistrer un commentaire