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 ...
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