1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.collections15.functors.closure;
17
18 import net.sf.collections15.Closure;
19
20 import java.io.Serializable;
21
22 /***
23 * <code>Closure</code> decorator that executes an existing <code>Closure</code>
24 * a specified number of times, like a <code>for</code> loop.
25 *
26 * @author Stephen Colebourne
27 * @author Chris Lambrou (port to Java 5.0)
28 * @since Collections15 1.0
29 */
30 public class ForClosure <E> implements Closure<E>, Serializable
31 {
32
33 static final long serialVersionUID = 4064412768376625993L;
34
35 /***
36 * The number of times to loop.
37 */
38 private final int count;
39
40 /***
41 * The closure to call.
42 */
43 private final Closure<? super E> closure;
44
45 /***
46 * Returns a new instance that executes the specified <code>Closure</code>
47 * the specified number of times.
48 *
49 * @param count The number of times to execute the <code>Closure</code>.
50 * @param closure The <code>Closure</code> to execute.
51 *
52 * @return A <code>ForClosure</code> that executes the specified
53 * <code>Closure</code> the specified number of times.
54 *
55 * @throws IllegalArgumentException Thrown if <code>count</code> < 0.
56 * @throws IllegalArgumentException Thrown if <code>closure</code> is
57 * <code>null</code>.
58 */
59 public static <T> ForClosure<T> decorate(int count, Closure<? super T> closure)
60 {
61 return new ForClosure<T>(count, closure);
62 }
63
64 /***
65 * Creates a new instance that executes the specified <code>Closure</code>
66 * the specified number of times.
67 *
68 * @param count The number of times to execute the <code>Closure</code>.
69 * @param closure The <code>Closure</code> to execute.
70 *
71 * @throws IllegalArgumentException Thrown if <code>count</code> < 0.
72 * @throws IllegalArgumentException Thrown if <code>closure</code> is
73 * <code>null</code>.
74 */
75 protected ForClosure(int count, Closure<? super E> closure)
76 {
77 if (count < 0) {
78 throw new IllegalArgumentException("negative count specified");
79 }
80 if (closure == null) {
81 throw new IllegalArgumentException("null closure");
82 }
83 this.count = count;
84 this.closure = closure;
85 }
86
87 /***
88 * Executes the <code>Closure, count</code> number of times.
89 *
90 * @param input The input object to act upon.
91 */
92 public void execute(E input)
93 {
94 for (int i = 0; i < count; i++) {
95 closure.execute(input);
96 }
97 }
98
99 /***
100 * Gets the decorated <code>Closure</code>.
101 *
102 * @return The decorated <code>Closure</code>.
103 *
104 * @since Collections15 1.0
105 */
106 public Closure<? super E> getClosure()
107 {
108 return closure;
109 }
110
111 /***
112 * Gets the number of times the decorated <code>Closure</code> is executed.
113 *
114 * @return The number of times the decorated <code>Closure</code> is
115 * executed.
116 *
117 * @since Collections15 1.0
118 */
119 public int getCount()
120 {
121 return count;
122 }
123
124 }