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 org.apache.commons.collections.functors;
  17. import java.io.Serializable;
  18. import org.apache.commons.collections.Factory;
  19. /**
  20. * Factory implementation that returns the same constant each time.
  21. * <p>
  22. * No check is made that the object is immutable. In general, only immutable
  23. * objects should use the constant factory. Mutable objects should
  24. * use the prototype factory.
  25. *
  26. * @since Commons Collections 3.0
  27. * @version $Revision: 1.5 $ $Date: 2004/05/16 11:47:38 $
  28. *
  29. * @author Stephen Colebourne
  30. */
  31. public class ConstantFactory implements Factory, Serializable {
  32. /** Serial version UID */
  33. static final long serialVersionUID = -3520677225766901240L;
  34. /** Returns null each time */
  35. public static final Factory NULL_INSTANCE = new ConstantFactory(null);
  36. /** The closures to call in turn */
  37. private final Object iConstant;
  38. /**
  39. * Factory method that performs validation.
  40. *
  41. * @param constantToReturn the constant object to return each time in the factory
  42. * @return the <code>constant</code> factory.
  43. */
  44. public static Factory getInstance(Object constantToReturn) {
  45. if (constantToReturn == null) {
  46. return NULL_INSTANCE;
  47. }
  48. return new ConstantFactory(constantToReturn);
  49. }
  50. /**
  51. * Constructor that performs no validation.
  52. * Use <code>getInstance</code> if you want that.
  53. *
  54. * @param constantToReturn the constant to return each time
  55. */
  56. public ConstantFactory(Object constantToReturn) {
  57. super();
  58. iConstant = constantToReturn;
  59. }
  60. /**
  61. * Always return constant.
  62. *
  63. * @return the stored constant value
  64. */
  65. public Object create() {
  66. return iConstant;
  67. }
  68. /**
  69. * Gets the constant.
  70. *
  71. * @return the constant
  72. * @since Commons Collections 3.1
  73. */
  74. public Object getConstant() {
  75. return iConstant;
  76. }
  77. }