Class ShortCircuitedGeometryVisitor

 1 /*
 2  * Copyright (c) 2016 Vivid Solutions.
 3  *
 4  * All rights reserved. This program and the accompanying materials
 5  * are made available under the terms of the Eclipse Public License 2.0
 6  * and Eclipse Distribution License v. 1.0 which accompanies this distribution.
 7  * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v20.html
 8  * and the Eclipse Distribution License is available at
 9  *
10  * http://www.eclipse.org/org/documents/edl-v10.php.
11  */
12  
13 package org.locationtech.jts.geom.util;
14  
15 import org.locationtech.jts.geom.Geometry;
16 import org.locationtech.jts.geom.GeometryCollection;
17  
18 /**
19  * A visitor to {@link Geometry} components, which
20  * allows short-circuiting when a defined condition holds.
21  *
22  * @version 1.7
23  */
24 public abstract class ShortCircuitedGeometryVisitor
25 {
26   private boolean isDone = false;
27  
28   public ShortCircuitedGeometryVisitor() {
29   }
30  
31   public void applyTo(Geometry geom) {
32     for (int i = 0; i < geom.getNumGeometries() && ! isDone; i++) {
33       Geometry element = geom.getGeometryN(i);
34       if (! (element instanceof GeometryCollection)) {
35         visit(element);
36         if (isDone()) {
37           isDone = true;
38           return;
39         }
40       }
41       else
42         applyTo(element);
43     }
44   }
45  
46   protected abstract void visit(Geometry element);
47  
48   /**
49    * Reports whether visiting components can be terminated.
50    * Once this method returns <tt>true</tt>, it must 
51    * continue to return <tt>true</tt> on every subsequent call.
52    * 
53    * @return true if visiting can be terminated.
54    */
55   protected abstract boolean isDone();
56 }
57