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 */
017package org.apache.commons.collections4.functors;
018
019import java.io.Serializable;
020
021import org.apache.commons.collections4.Closure;
022import org.apache.commons.collections4.Transformer;
023
024/**
025 * Closure implementation that calls a Transformer using the input object
026 * and ignore the result.
027 *
028 * @param <T> the type of the input to the operation.
029 * @since 3.0
030 */
031public class TransformerClosure<T> implements Closure<T>, Serializable {
032
033    /** Serial version UID */
034    private static final long serialVersionUID = -5194992589193388969L;
035
036    /**
037     * Factory method that performs validation.
038     * <p>
039     * A null transformer will return the {@code NOPClosure}.
040     *
041     * @param <E> the type that the closure acts on
042     * @param transformer  the transformer to call, null means nop
043     * @return the {@code transformer} closure
044     */
045    public static <E> Closure<E> transformerClosure(final Transformer<? super E, ?> transformer) {
046        if (transformer == null) {
047            return NOPClosure.<E>nopClosure();
048        }
049        return new TransformerClosure<>(transformer);
050    }
051
052    /** The transformer to wrap */
053    private final Transformer<? super T, ?> iTransformer;
054
055    /**
056     * Constructor that performs no validation.
057     * Use {@code transformerClosure} if you want that.
058     *
059     * @param transformer  the transformer to call, not null
060     */
061    public TransformerClosure(final Transformer<? super T, ?> transformer) {
062        iTransformer = transformer;
063    }
064
065    /**
066     * Executes the closure by calling the decorated transformer.
067     *
068     * @param input  the input object
069     */
070    @Override
071    public void execute(final T input) {
072        iTransformer.apply(input);
073    }
074
075    /**
076     * Gets the transformer.
077     *
078     * @return the transformer
079     * @since 3.1
080     */
081    public Transformer<? super T, ?> getTransformer() {
082        return iTransformer;
083    }
084
085}