Common Java Cookbook

Edition: 0.19

Download PDF or Read on Scribd

Download Examples (ZIP)

4.10. Transforming Objects

4.10.1. Problem

You need to perform a transformation, taking an object and creating a new object.

4.10.2. Solution

Implement the Transformer interface. A Transformer takes an object and returns a new object instance. The following example demonstrates the joinArmy Transformer; the transform( ) method takes a Recruit object instance and returns a Soldier object:

import org.apache.commons.collections.Transformer;
Transformer joinArmy = new Transformer( ) {
    public Object transform(Object input) {
                Recruit recruit = (Recruit) input;
         BootCamp.obstacleCourse( recruit );
                Soldier soldier = BootCamp.graduate( recruit );
        }
}
Recruit recruit1 = new Recruit("Pat T.");
System.out.println( "Status before transformation: " + recruit );
Soldier soldier1 = (Soldier) joinArmy.transform( recruit1 );
System.out.println( "Status after transformation: " + soldier );

A Recruit object is passed to the joinArmy.transform( ) method, and a Soldier object is returned. The state of the recruit and soldier instances are printed before and after the transformation:

Status before transformation: Pat T., Recruit
Status after transformation: Pat T., Soldier

4.10.3. Discussion

This object isolates and encapsulates a transition; a system that needs to translate between two domain models or two object types should encapsulate such a transition in a Transformer. Transformer may be something of a misnomer. When an object undergoes a transformation, it is common to think of an object being modified or acted upon, but this is contrary to the design of the Transformer interface. The Javadoc for Transformer expressly states, "The original object is left unchanged." Figure 4-3 illustrates the simple joinArmy Transformer.

Diagram of the joinArmy Transformer

Figure 4-3. Diagram of the joinArmy Transformer



Creative Commons License
Common Java Cookbook by Tim O'Brien is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License.
Permissions beyond the scope of this license may be available at http://www.discursive.com/books/cjcook/reference/jakartackbk-PREFACE-1.html. Copyright 2009. Common Java Cookbook Chunked HTML Output. Some Rights Reserved.