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 * @since 3.0
32 */
33 public class ConstantFactory<T> implements Factory<T>, Serializable {
34
35 /** Serial version UID */
36 private static final long serialVersionUID = -3520677225766901240L;
37
38 /** Returns null each time */
39 @SuppressWarnings("rawtypes") // The null factory works for all object types
40 public static final Factory NULL_INSTANCE = new ConstantFactory<>(null);
41
42 /**
43 * Factory method that performs validation.
44 *
45 * @param <T> the type of the constant
46 * @param constantToReturn the constant object to return each time in the factory
47 * @return the {@code constant} factory.
48 */
49 public static <T> Factory<T> constantFactory(final T constantToReturn) {
50 if (constantToReturn == null) {
51 return NULL_INSTANCE;
52 }
53 return new ConstantFactory<>(constantToReturn);
54 }
55
56 /** The closures to call in turn */
57 private final T iConstant;
58
59 /**
60 * Constructor that performs no validation.
61 * Use {@code constantFactory} if you want that.
62 *
63 * @param constantToReturn the constant to return each time
64 */
65 public ConstantFactory(final T constantToReturn) {
66 iConstant = constantToReturn;
67 }
68
69 /**
70 * Always return constant.
71 *
72 * @return the stored constant value
73 */
74 @Override
75 public T create() {
76 return iConstant;
77 }
78
79 /**
80 * Gets the constant.
81 *
82 * @return the constant
83 * @since 3.1
84 */
85 public T getConstant() {
86 return iConstant;
87 }
88
89 }