
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Performing Multiple Operations on a List Using Functors
|
553
Solution
Use a functor (or function object as it is also known) as the vehicle for transforming
the collection. A functor is any object that can be called as a function. Examples of
this are a function, a function pointer, or even an object that defines
operator () for
us C/C++ converts.
Needing to perform multiple operations on a collection is a reasonably common
thing in software. Let’s say that you have a stock portfolio with a bunch of stocks in
it. Your
StockPortfolio class would have a List of Stock objects. It would be able to
be created with an initial capacity, and it would have the ability to add stocks.
public class StockPortfolio
{
List<Stock> _stocks;
public StockPortfolio(int capacity)
{
_stocks = new List<Stock>(capacity);
}
public void AddStock(string ticker, double gainLoss)
{
_stocks.Add(new Stock(ticker, gainLoss));
}
More methods down here...
}
The Stock class is rather simple. You just need a ticker symbol for the stock and its
percentage of gain or loss:
public class Stock
{
string _tickerSymbol;
double _gainLoss;
public Stock(string ticker, double gainLoss)
{
_tickerSymbol = ticker;
_gainLoss = gainLoss;
}
public double GainLoss {get { return _gainLoss; } }
public string Ticker {get { return _tickerSymbol; ...