Cover Data Structures and Algorithms with Object-Oriented Design Patterns in Java
next up previous contents index

The isDone Method

As shown in Program gif, the Visitor interface also includes the method isDone. The isDone method is an accessor which is used to determine whether a visitor has finished its work. That is, the isDone method returns the boolean value true if the visitor ``is done.''

The idea is this: Sometimes a visitor does not need to visit all the objects in a container. That is, in some cases, the visitor may be finished its task after having visited only a some of the objects. The isDone method can be used by the container to terminate the accept method early like this:

public class SomeContainer
    implements Container

public void accept (Visitor visitor)

for each Object i in this container

if (visitor.isDone ()) return; visitor.visit (i);

// ...

To illustrate the usefulness of isDone, consider a visitor which visits the objects in a container with the purpose of finding the first object that matches a given target object. Having found the first matching object in the container, the visitor is done and does not need to visit any more contained objects.

The following code fragment defines a visitor which finds the first object in the container that matches a given object.

public class MatchingVisitor
    implements Visitor
{
    private Object target;
    private Object found;

    public MatchingVisitor (Object target)
	{ this.target = target; }

    public void visit (Object object)
    {
	if (!isDone () && object.equals (target))
            found = object;
    }

    public boolean isDone ()
        { return found != null; }
}

The constructor of the MatchingVisitor visitor takes a reference to an Object instance that is the target of the search. That is, we wish to find an object in a container that matches the target. For each object the MatchingVisitor visitor visits, it compares that object with the target and makes found point at that object if it matches. Clearly, the MatchingVisitor visitor is done when the found pointer is non-zero.

Suppose we have a container c that is an instance of a concrete container class, SomeContainer, that implements the Container interface; and an object x that is an instance of a concrete object class, SomeObject. Then, we can call use the MatchingVisitor visitor as follows:

Container c = new SomeContainer ();
Object x = new SomeObject ();
// ...
c.accept (new MatchingVisitor (x));


next up previous contents index

Bruno Copyright © 1998 by Bruno R. Preiss, P.Eng. All rights reserved.