Design Patterns Java™ Workbook

(Michael S) #1
Appendix B. Solutions

Visitor (Chapter 29)....................................................................................................................................


SOLUTION 29.1....................................................................................................................................


The difference is in the type of the this object. The accept() method calls the visit()
method of a MachineVisitor object. The accept() method in the Machine class will
look up a visit() method with the signature visit(Machine), whereas the accept()
method in the MachineComposite class will look up a method with the signature
visit(MachineComposite).


SOLUTION 29.2....................................................................................................................................


One solution is:


package com.oozinoz.applications;
import com.oozinoz.machine.;
import com.oozinoz.dublin.
;
public class ShowFind
{
public static void main(String[] args)
{
MachineComponent f = OozinozFactory.dublin();
System.out.println(new FindVisitor().find(f, 3404));
}
}


This program successfully prints out:


StarPress3404


SOLUTION 29.3....................................................................................................................................


A solution is:


package com.oozinoz.dublin;
import com.oozinoz.machine.;
import java.util.
;
public class RakeVisitor extends MachineVisitor
{
private Set leaves;
public Set getLeaves(MachineComponent mc)
{
leaves = new HashSet();
mc.accept(this);
return leaves;
}


public void visit(Machine m)
{
leaves.add(m);
}

Free download pdf