4.13. Writing a Closure

Problem

You need a functor that operates on an object.

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

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.

See Also

Jakarta Commons Functor in the Commons Sandbox expands on the initial functors introduced in Commons Collections, introducing a UnaryProcedure object that provides a simple interface equivalent to Closure. For more information about UnaryProcedure, see the Commons Functor page at http://jakarta.apache.org/commons/sandbox/functor.

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.