4.11. Creating a Chain of Transformations
Problem
You have a series of transformations and you need to chain them together, passing the output of one stage to the input of the next.
Solution
Create multiple implementations of Transformer,
and chain them together with ChainedTransformer. A
ChainedTransformer
takes an array of Transformer objects, passing the
output of each Transformer to the next
Transformer in the chain. The following example
demonstrates a ChainedTransformer with two
Transformer stages. The first stage,
multiply, multiplies a number by 100, and the
second stage, increment, adds one to the result
from the first stage:
import org.apache.commons.collections.Transformer;
import org.apache.commons.collections.functors.ChainedTransformer;
Transformer multiply = new Transformer( ) {
public Object transform(Object input) {
Long number = (Long) input;
return( new Long( number.longValue( ) * 100 ) );
}
}
Transformer increment = new Transformer( ) {
public Object transform(Object input) {
Long number = (Long) input;
return( new Long( number.longValue( ) + 1 ) );
}
}
Transformer[] chainElements = new Transformer[] { multiply, increment };
Transformer chain = new ChainedTransformer( chainElements );
Long original = new Long( 34 );
Long result = chain.transform( original );
System.out.println( "Original: " + original );
System.out.println( "Result: " + result );The Transformer chain takes the
Long instance original and
transforms it into a result:
Original: 34 Result: 3401
Discussion ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access