001/* 002 * Licensed under the Apache License, Version 2.0 (the "License"); 003 * you may not use this file except in compliance with the License. 004 * You may obtain a copy of the License at 005 * 006 * http://www.apache.org/licenses/LICENSE-2.0 007 * 008 * Unless required by applicable law or agreed to in writing, software 009 * distributed under the License is distributed on an "AS IS" BASIS, 010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 011 * See the License for the specific language governing permissions and 012 * limitations under the License. 013 */ 014 015package org.apache.commons.functor.generator.loop; 016 017import org.apache.commons.functor.generator.BaseGenerator; 018import org.apache.commons.functor.generator.Generator; 019 020/** 021 * Base class for generators that control execution flow, and may need to 022 * stop the generation. 023 * 024 * @param <E> the type of elements held in this generator. 025 * @since 1.0 026 * @version $Revision$ $Date$ 027 */ 028public abstract class LoopGenerator<E> extends BaseGenerator<E> { 029 030 /** A generator can wrap another generator. */ 031 private final Generator<? extends E> wrappedGenerator; 032 033 /** Set to true when the generator is {@link #stop stopped}. */ 034 private boolean stopped = false; 035 036 /** Create a new generator. */ 037 public LoopGenerator() { 038 this(null); 039 } 040 041 /** 042 * A generator can wrap another generator. When wrapping generators you 043 * should use probably this constructor since doing so will cause the 044 * {@link #stop} method to stop the wrapped generator as well. 045 * @param generator Generator to wrap 046 */ 047 public LoopGenerator(Generator<? extends E> generator) { 048 this.wrappedGenerator = generator; 049 } 050 051 /** 052 * Get the generator that is being wrapped. 053 * @return Generator 054 */ 055 protected Generator<? extends E> getWrappedGenerator() { 056 return wrappedGenerator; 057 } 058 059 /** 060 * Stop the generator. Will stop the wrapped generator if one was set. 061 */ 062 public void stop() { 063 if (wrappedGenerator != null && wrappedGenerator instanceof LoopGenerator<?>) { 064 ((LoopGenerator<?>) wrappedGenerator).stop(); 065 } 066 stopped = true; 067 } 068 069 /** 070 * Check if the generator is stopped. 071 * @return <code>true</code> if the generator is stopped, <code>false</code> 072 * otherwise 073 */ 074 public boolean isStopped() { 075 return stopped; 076 } 077 078}