Java Reference
In-Depth Information
Figure 10-7 shows a CRC card for the class
StockLedger
. The class enables us to record stock
purchases in chronological order. At the time of sale, the class computes the capital gain and
updates the record of stocks owned. These last two steps are related, so we combine them into one
method. Thus, the class has two methods,
buy
and
sell
, as Figure 10-8 illustrates.
FIGURE 10-7
A CRC card for the class
StockLedger
StockLedger
Responsibilities
Record the shares of a stock purchased, in
chronological order
Remove the shares of a stock sold, beginning
with the ones held the longest
Compute the capital gain (loss) on shares of a
stock sold
Collaborations
Share of stock
FIGURE 10-8
A diagram of the classes
StockLedger
and
StockPurchase
StockLedger
*
ledger
—a collection of shares owned, in order of their purchase
buy(sharesBought, pricePerShare)
sell(sharesSold, pricePerShare)
StockPurchase
*
cost
—cost of one share
getCostPerShare()
The following statements demonstrate how we could use
StockLedger
to record the transac-
tions given in the problem description:
StockLedger myStocks =
new
StockLedger();
myStocks.buy(20, 45);
// buy 20 shares at $45
myStocks.buy(20, 75);
// buy 20 shares at $75
double
capGain = myStocks.sell(30, 65);
// sell 30 shares at $65
10.11
Implementation.
In this example,
StockLedger
records instances of
StockPurchase
—which rep-
resent the shares we own—in a queue. A queue orders the shares chronologically, so we can sell
them in the order in which we purchased them. The method
buy
then just enqueues each share that
is bought.
The method
sell
removes from the queue as many shares as are sold. As it does this, it computes
the total capital gain from the sale and returns it. The class
StockLedger
is given in Listing 10-3.