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.Transformer;
  19. /**
  20. * Transformer 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:36:31 $
  28. *
  29. * @author Stephen Colebourne
  30. */
  31. public class ConstantTransformer implements Transformer, Serializable {
  32. /** Serial version UID */
  33. static final long serialVersionUID = 6374440726369055124L;
  34. /** Returns null each time */
  35. public static final Transformer NULL_INSTANCE = new ConstantTransformer(null);
  36. /** The closures to call in turn */
  37. private final Object iConstant;
  38. /**
  39. * Transformer 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 Transformer getInstance(Object constantToReturn) {
  45. if (constantToReturn == null) {
  46. return NULL_INSTANCE;
  47. }
  48. return new ConstantTransformer(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 ConstantTransformer(Object constantToReturn) {
  57. super();
  58. iConstant = constantToReturn;
  59. }
  60. /**
  61. * Transforms the input by ignoring it and returning the stored constant instead.
  62. *
  63. * @param input the input object which is ignored
  64. * @return the stored constant
  65. */
  66. public Object transform(Object input) {
  67. return iConstant;
  68. }
  69. /**
  70. * Gets the constant.
  71. *
  72. * @return the constant
  73. * @since Commons Collections 3.1
  74. */
  75. public Object getConstant() {
  76. return iConstant;
  77. }
  78. }