Java Reference
In-Depth Information
The figure doesn't explain how V ISITOR works; the next section does that. The figure simply
shows some of the groundwork that lets you apply V ISITOR .
One aspect of allowing for later extensions is that the hierarchy classes make their attributes
accessible. In particular, the getId() method of the MachineComponent class and the
getComponents() method of the MachineComposite class make it possible for visitors
to access these critical attri-butes of hierarchy objects. The mechanics of providing support
for V ISITOR also include adding an accept() operation to the hierarchy and adding a visitor
interface that developers can implement to create new extensions.
The accept() method in the MachineComponent class is abstract. Both subclasses
implement this method with exactly the same code:
public void accept(MachineVisitor v)
{
v.visit(this);
}
You might think that because this method is identical in the Machine and
MachineComposite class, you could move the method up to the abstract
MachineComponent class. However, a compiler will see a difference in these two
"identical" methods.
CHALLENGE 29.1
What difference will a Java compiler see between the accept() methods in the
Machine and MachineComposite classes?
The MachineVisitor interface requires implementers to define methods for visiting
machines and machine composites:
package com.oozinoz.machine;
public interface MachineVisitor
{
void visit(Machine m);
void visit(MachineComposite mc);
}
The accept() methods in the MachineComponent , together with the visitor interface,
invite developers to provide new operations to the hierarchy.
Extending with Visitor
Suppose that you accept an assignment to help bring up a new Oozinoz factory in Dublin,
Ireland. The developers in Dublin have created an object model of the new factory's machine
composition and have made this model accessible as the static dublin() method of
the OozinozFactory class. To display this composite, the developers created
Search WWH ::




Custom Search