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