Common Java Cookbook

Edition: 0.19

Download PDF or Read on Scribd

Download Examples (ZIP)

4.13. Writing a Closure

4.13.1. Problem

You need a functor that operates on an object.

4.13.2. Solution

Use a Closure to encapsulate a block of code that acts on an object. In this example, a discount Closure operates on a Product object, reducing the price by 10 percent:

Closure discount = new Closure( ) {
    int count = 0;
    public int getCount( ) { return count; }
  
    public void execute(Object input) {
        count++;
            (Product) product = (Product) input;
            product.setPrice( product.getPrice( ) * 0.90 ); 
    }
}
Product shoes = new Product( );
shoes.setName( "Fancy Shoes" );
shoes.setPrice( 120.00 );
System.out.println( "Shoes before discount: " + shoes );
discount.execute( shoes );
System.out.println( "Shoes after discount: " + shoes );
discount.execute( shoes );
discount.execute( shoes );
System.out.println( "Shoes after " + discount.getcount( ) + 
                    " discounts: " + shoes );

The example prints out the original cost of shoes ($120) and then proceeds to discount shoes and print out the discounted price. The Product object, shoes, is modified by the discount Closure three separate times:

Shoes before discount: Fancy Shoes for $120.00
Shoes after discount: Fancy Shoes for $108.00
Shoes after 3 discounts: Fancy Shoes for $87.48

4.13.3. Discussion

A Closure operates on the input object passed to the execute( ) method, while a Transformer does not alter the object passed to transform( ). Use Closure if your system needs to act on an object. Like the Transformer and Predicate interfaces, there are a number of Closure implementations that can be used to chain and combine Closure instances.


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.