1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.commons.collections4.functors;
18
19 import java.io.Serializable;
20
21 import org.apache.commons.collections4.Factory;
22
23 /**
24 * Factory implementation that returns the same constant each time.
25 * <p>
26 * No check is made that the object is immutable. In general, only immutable
27 * objects should use the constant factory. Mutable objects should
28 * use the prototype factory.
29 * </p>
30 *
31 * @param <T> the type of results supplied by this supplier.
32 * @since 3.0
33 */
34 public class ConstantFactory<T> implements Factory<T>, Serializable {
35
36 /** Serial version UID */
37 private static final long serialVersionUID = -3520677225766901240L;
38
39 /** Returns null each time */
40 @SuppressWarnings("rawtypes") // The null factory works for all object types
41 public static final Factory NULL_INSTANCE = new ConstantFactory<>(null);
42
43 /**
44 * Factory method that performs validation.
45 *
46 * @param <T> the type of the constant
47 * @param constantToReturn the constant object to return each time in the factory
48 * @return the {@code constant} factory.
49 */
50 public static <T> Factory<T> constantFactory(final T constantToReturn) {
51 if (constantToReturn == null) {
52 return NULL_INSTANCE;
53 }
54 return new ConstantFactory<>(constantToReturn);
55 }
56
57 /** The closures to call in turn */
58 private final T iConstant;
59
60 /**
61 * Constructor that performs no validation.
62 * Use {@code constantFactory} if you want that.
63 *
64 * @param constantToReturn the constant to return each time
65 */
66 public ConstantFactory(final T constantToReturn) {
67 iConstant = constantToReturn;
68 }
69
70 /**
71 * Always return constant.
72 *
73 * @return the stored constant value
74 */
75 @Override
76 public T create() {
77 return iConstant;
78 }
79
80 /**
81 * Gets the constant.
82 *
83 * @return the constant
84 * @since 3.1
85 */
86 public T getConstant() {
87 return iConstant;
88 }
89
90 }