1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.collections15.functors.transformer;
17
18 import net.sf.collections15.Transformer;
19
20 import java.io.Serializable;
21
22 /***
23 * <code>Transformer</code> implementation that returns the same constant each
24 * time.
25 * <p/>
26 * No check is made that the object is immutable. In general, only immutable
27 * objects should use the <code>ConstantTransformer</code>. Mutable objects
28 * should use the {@link FactoryTransformer}, seeded with a {@link
29 * net.sf.collections15.functors.factory.PrototypeFactory PrototypeFactory}
30 *
31 * @author Stephen Colebourne
32 * @author Chris Lambrou (port to Java 5.0)
33 * @since Collections15 1.0
34 */
35 public class ConstantTransformer <I, O> implements Transformer<I, O>, Serializable
36 {
37
38 static final long serialVersionUID = 6266774234958279132L;
39
40 /***
41 * The constant returned by the transform.
42 */
43 private final O constant;
44
45 /***
46 * Returns an instance whose {@link #transform} method always returns the
47 * specified constant.
48 *
49 * @param constant The constant to be returned each time the {@link
50 * #transform} method is invoked. May be <code>null</code>.
51 *
52 * @return An instance whose {@link #transform} method always returns the
53 * specified constant.
54 */
55 public static <I, O> ConstantTransformer<I, O> getInstance(O constant)
56 {
57 return new ConstantTransformer<I, O>(constant);
58 }
59
60 /***
61 * Creates a new instance whose {@link #transform} method always returns the
62 * specified constant.
63 *
64 * @param constant The constant to be returned each time the {@link
65 * #transform} method is invoked. May be <code>null</code>.
66 */
67 protected ConstantTransformer(O constant)
68 {
69 this.constant = constant;
70 }
71
72 /***
73 * Transforms the input by ignoring it and returning the stored constant
74 * instead.
75 *
76 * @param input The input object which is ignored.
77 *
78 * @return The stored constant.
79 */
80 public O transform(I input)
81 {
82 return constant;
83 }
84
85 /***
86 * Returns the constant used by this <code>Transformer</code>.
87 *
88 * @return The constant used by this <code>Transformer</code>.
89 *
90 * @since Collections15 1.0
91 */
92 public O getConstant()
93 {
94 return constant;
95 }
96
97 }