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

The IsDone Property

As shown in Program gif, the Visitor interface also includes the property IsDone. The IsDone property provides a get accessor that is used to determine whether a visitor has finished its work. That is, the IsDone method returns the bool 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 : Container
{
    public void Accept(Visitor visitor)
    {
	foreach (object i in this)
	{
            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 : Visitor
{
    private object target;
    private object found;

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

    public void Visit(object obj)
    {
	if (!IsDone && obj.equals(target))
            found = obj;
    }

    public bool 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 © 2001 by Bruno R. Preiss, P.Eng. All rights reserved.