November 2004
Intermediate to advanced
400 pages
10h 31m
English
You need to model a conditional statement with functors.
Use an IfClosure, supplying a
Predicate and two Closure
objects. If the Predicate evaluates to
true, the first Closure is
executed; if the Predicate evaluates to
false, the second Closure is
executed. The following closure deals with a financial decision; a
Predicate, isWinning, evaluates
a Stock object. If the purchase price is less than
the current price, the stock is a winner, causing the
buy
Closure to be executed. If
the purchase price is higher than the current price, the stock is a
loser and it is sold by passing it to the sell
Closure:
Closure sell = new Closure( ) { public void execute(Object input) { Stock stock = (Stock) input; stock.sell( stock.getShares( ) ); System.out.println( "\tSold all shares" ); } } Closure buy = new Closure( ) { public void execute(Object input) { Stock stock = (Stock) input; int buyShares = stock.getShares( ) * 0.10; stock.buy( buyShares ); System.out.println( "\tBought " + buyShares ); } } Predicate isWinning = new Predicate( ) { public boolean evaluate(Object object) { Stock stock = (Stock) object; if( stock.getPurchasePrice( ) < stock.getCurrentPrice( ) ) { System.out.println( stock.getSymbol( ) + " is a winner"; return true; } else { System.out.println( stock.getSymbol( ) + " is a loser"; return false; } } } Closure stockAction = new IfClosure( isWinning, buy, sell ); Stock yahoo = new Stock("YHOO"); yahoo.setPurchasePrice( ...Read now
Unlock full access