Download presentation
Presentation is loading. Please wait.
1
Interpreter Presented by: Joey Richey T.J. Emond
2
Metsker’s Definition ● The intent of the Interpreter pattern is: – “Define a class hierarchy that represents a grammer - a set of composition rules - and define an operation throughout this hierarchy to interpret, or bring meaning to, instances of the set of possible compositions”
3
What it is good for ● A language with a simple grammar ● Efficency is not a prime concern ● Easy to change grammar ● Easy to implement ● Easily add new ways to interpret expressions
4
Regular Expression (Grammar) Expression ::= literal | alternation | sequence | repetition | '(' expression ')' alternation ::= expression '|' expression sequence ::= expression '&' expression repetition ::= expression '*' literal := 'a' | 'b' | 'c' |... {'a' | 'b' | 'c' |...} *
5
Regular Expression (Class Diagram)
6
Regular Expression (Parse Tree) “ Raining & (dogs | cats) * ”
7
Ifs ● Term has eval() method that returns a Machine object ● Context maps machine names to instances of Machine ● eval() returning null represents false public class IfCommand extends Command { protected Term term; protected Command body; protected Command elseBody; public IfCommand( Term term, Command body, Command elseBody) { this.term = term; this.body = body; this.elseBody = elseBody; } public void execute(Context c) { if (term.eval(c) != null) { body.execute(c); } else { elseBody.execute(c); }
8
Challenge ● Write code for WhileCommand.java
9
Solution public class WhileCommand extends Command { protected Term term; protected Command body; public WhileCommand(Term term, Command body) { this.term = term; this.body = body; } public void execute(Context c) { while (term.eval(c) != null) { body.execute(c); }
10
Something useful ● HasMaterial’s eval() method again returns a Machine or null ● We can use a WhileCommand now public class HasMaterial extends Term { protected Term term; public HasMaterial(Term term) { this.term = term; } public Machine eval(Context c) { Machine m = term.eval(c); return m.hasMaterial() ? m : null; } WhileCommand wc = new WhileCommand( new HasMaterial(machineConstant), new CarryCommand(machineConstant, machineConstant2)); wc.execute(aContext);
11
Challenge ● What is the difference, if any, between the Command and Interpreter patterns?
12
Solution ● Command – Attempt is to encapsulate a request in an object – Done on a command-by-command basis ● Interpreter – Attempt is to define classes that interpret an operation based on its composition – Can create an infinite “language”
13
Conclusion Any Questions?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.