001 /* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 package org.apache.commons.collections.functors; 018 019 import java.io.Serializable; 020 021 import org.apache.commons.collections.Transformer; 022 023 /** 024 * Transformer implementation that returns the same constant each time. 025 * <p> 026 * No check is made that the object is immutable. In general, only immutable 027 * objects should use the constant factory. Mutable objects should 028 * use the prototype factory. 029 * 030 * @since Commons Collections 3.0 031 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $ 032 * 033 * @author Stephen Colebourne 034 */ 035 public class ConstantTransformer implements Transformer, Serializable { 036 037 /** Serial version UID */ 038 private static final long serialVersionUID = 6374440726369055124L; 039 040 /** Returns null each time */ 041 public static final Transformer NULL_INSTANCE = new ConstantTransformer(null); 042 043 /** The closures to call in turn */ 044 private final Object iConstant; 045 046 /** 047 * Transformer method that performs validation. 048 * 049 * @param constantToReturn the constant object to return each time in the factory 050 * @return the <code>constant</code> factory. 051 */ 052 public static Transformer getInstance(Object constantToReturn) { 053 if (constantToReturn == null) { 054 return NULL_INSTANCE; 055 } 056 return new ConstantTransformer(constantToReturn); 057 } 058 059 /** 060 * Constructor that performs no validation. 061 * Use <code>getInstance</code> if you want that. 062 * 063 * @param constantToReturn the constant to return each time 064 */ 065 public ConstantTransformer(Object constantToReturn) { 066 super(); 067 iConstant = constantToReturn; 068 } 069 070 /** 071 * Transforms the input by ignoring it and returning the stored constant instead. 072 * 073 * @param input the input object which is ignored 074 * @return the stored constant 075 */ 076 public Object transform(Object input) { 077 return iConstant; 078 } 079 080 /** 081 * Gets the constant. 082 * 083 * @return the constant 084 * @since Commons Collections 3.1 085 */ 086 public Object getConstant() { 087 return iConstant; 088 } 089 090 }