Design Patterns Java™ Workbook

(Michael S) #1
Appendix B. Solutions

Interpreter (Chapter 25)............................................................................................................................


SOLUTION 25.1....................................................................................................................................


The following program will shut down all the machines that MachineLine controls, except
for the unload buffer:


package com.oozinoz.robot.interpreter;
import com.oozinoz.machine.*;
public class ShowIf
{
public static void main(String[] args)
{
Context c = MachineLine.createContext();
Variable m = new Variable("m");
Constant ub =
new Constant(c.lookup("UnloadBuffer1501"));
Term t = new Equals(m, ub);


IfCommand ic =
new IfCommand(
t,
new NullCommand(),
new ShutdownCommand(m));
ForMachines fc = new ForMachines(m, ic);
fc.execute(c);
}
}


The fc object is an interpreter; it interprets execute() to mean shut down all machines
except the unload buffer.


SOLUTION 25.2....................................................................................................................................


One solution is:


package com.oozinoz.robot.interpreter;
import com.oozinoz.machine.*;
public class WhileCommand extends Command
{
protected Term term;
protected Command body;


public WhileCommand(Term term, Command body)
{
this.term = term;
this.body = body;
}

Free download pdf