View Javadoc

1   /*
2    *  Copyright 2001-2004 The Apache Software Foundation
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   */
16  package net.sf.collections15.functors.factory;
17  
18  import net.sf.collections15.Factory;
19  
20  import java.io.Serializable;
21  
22  /***
23   * <code>Factory</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>ConstantFactory</code>. Mutable objects should
28   * use the {@link PrototypeFactory} instead.
29   *
30   * @author Stephen Colebourne
31   * @author Chris Lambrou (port to Java 5.0)
32   * @since Collections15 1.0
33   */
34  public class ConstantFactory <E> implements Factory<E>, Serializable
35  {
36  
37      static final long serialVersionUID = 6266774234958279132L;
38  
39      /***
40       * The object returned by the factory.
41       */
42      private final E constant;
43  
44      /***
45       * Factory method that performs validation.
46       *
47       * @param constantToReturn the constant object to return each time in the
48       *                         factory
49       *
50       * @return the <code>constant</code> factory.
51       */
52      public static <E> ConstantFactory<E> getInstance(E constantToReturn)
53      {
54          return new ConstantFactory<E>(constantToReturn);
55      }
56  
57      /***
58       * Creates a new instance that returns the specified constant.
59       *
60       * @param constantToReturn The constant to return each time. May be
61       *                         <code>null</code>.
62       */
63      protected ConstantFactory(E constantToReturn)
64      {
65          constant = constantToReturn;
66      }
67  
68      /***
69       * Always returns the stored constant value.
70       *
71       * @return The stored constant value
72       */
73      public E create()
74      {
75          return constant;
76      }
77  
78      /***
79       * Gets the stored constant value.
80       *
81       * @return The stored constant value.
82       *
83       * @since Collections15 1.0
84       */
85      public E getConstant()
86      {
87          return constant;
88      }
89  
90  }