The **Observer** class allows observables to be registered and unregistered using the following methods.

std::pair< std::set<boost::shared_ptr<Observable> >::iterator, bool > registerWith(const boost::shared_ptr<Observable>&); Size unregisterWith(const boost::shared_ptr<Observable>&); void unregisterWithAll();

The **registerWith()** method will register the observer with a particular observable. This means that the observer will be notified when the observable changes. The method **unregisterWith()** will remove the observer from the list of objects to be notified when the observable changes, and **unregisterWithAll()** will unregister the observer with all observables that it might be registered with.

virtual void update() = 0;

When the observable changes it will cause the update function of all its registered observers to be called. This function should be implemented by a concrete observer class to take whatever actions should be taken when the observable changes.

The Observable class defines one central method.

void notifyObservers();

This method will notify all the registered observers of changes in the observable and cause the **update()** function of each of these to be called. A concrete observable class should call the **notifyObservers()** function whenever its internal state has changed.

Let’s look at an example to understand exactly how the observer pattern works.

class MyObservable : public Observable { private: Real amount; Natural year; public: void calculateInterest(Real amount, Real rate, Natural years) { this->amount = amount; this->year = 0; notifyObservers(); for (this->year=1; this->year<=years; ++this->year) { this->amount = this->amount*(1.0 + rate); notifyObservers(); } } Real getAmount() { return this->amount; } }; typedef boost::shared_ptr<MyObservable> pMyObservable; class MyObserver : public Observer { private: pMyObservable observable; std::string name; public: MyObserver(pMyObservable obs, std::string n) : observable(obs), name(n) { this->registerWith(observable); } MyObserver(const MyObserver &observer) : Observer(observer), observable(observer.observable), name("Copy of "+observer.name) {} void update() { std::cout << name << " " << observable->getAmount() << std::endl; } }; int main() { pMyObservable calc(new MyObservable); MyObserver observerA(calc, "observer a"); MyObserver observerB(calc, "observer b"); std::cout << "First calculation" << std::endl; calc->calculateInterest(100.0, 0.03, 5); observerB.unregisterWith(calc); std::cout << "Second calculation" << std::endl; calc->calculateInterest(100.0, 0.04, 5); return 0; }

The MyObservable class defines a method called **calculateInterest()** which will add the interest onto a given amount for a set number of years. Every time that the amount is updated, the observable calls the **notifyObservers()** method which is implemented in the Observable class. This in turn will call the update method of every observer. The **main()** function creates an object of type MyObservable named calc. It then creates two observers which register themselves with the observable in their constructor. After this the **calculateInterest()** method is called. During this first calculation both observers are registered with the observable and, thus,both will print out the accrued amount after every year. After this calculation the second observer is un-registered with the observable after which a second calculation is carried out. This time only the first observer reacts to the changes. The output of the example is written out below.

observer a 100 observer b 100 observer a 103 observer b 103 observer a 106.09 observer b 106.09 observer a 109.273 observer b 109.273 observer a 112.551 observer b 112.551 observer a 115.927 observer b 115.927 Second calculation observer a 100 observer a 104 observer a 108.16 observer a 112.486 observer a 116.986 observer a 121.665

The behavior of the **Observer** and the **Observable** classes with respect to copying might be slightly unexpected. When copying one observer to another, either by the copy constructor or by the assignment operator, then the new observer will also be registered with all the observables which the original observer was registered with. On the other hand, when copying an observable the observable so created or modified will not notify the observers of the assigning object. When the value is changed with the assignment operator then the object which is changed will notify its observers. The philosophy behind this is that a newly created observable is not the one that the observer has registered with.

To illustrate we extend the **main()** function in the above example.

pMyObservable calc2(new MyObservable(calc)); std::cout << "Third calculation" << std::endl; // The following line will not produce any outpt calc2->calculateInterest(); MyObserver observerC(observerA); std::cout << "Fourth calculation" << std::endl; // The following calculation will notify observerA and observerC calc->calculateInterest();

The calculations carried out by **calc2** will not notify any observer because the **calc2** observable has not copied the observers from the calculate object. The last calculation carried out by the original calculate object, on the other hand will notify both the **observerA** and **observerC** because observers automatically register with the observables when copied.

The constructor of the base class **Dividend** takes only the payment date of the dividend.

Dividend(const Date& date);

The date is stored in the **Dividend** object and can be inspected by the **date()** method.

Date date() const;

This method also implements the **Event** interface which **CashFlow** inherited from.

virtual Real amount() const = 0; virtual Real amount(Real underlying) const = 0;

The **amount()** method is re-declared from the **CashFlow** class and another amount method is added which takes the value of an underlying entity. Both method are abstract and are implemented by the **FixedDividend** and the **FractionalDividend** class.

virtual void accept(AcyclicVisitor&);

The **accept()** method allows visitation by the acyclic visitor.

The **FixedDividend** class implements a dividend with a fixed amount that is paid out at the specified date. The constructor takes the dividend amount and the date.

FixedDividend(Real amount, const Date& date)

Once the **FixedDividend** object is created, the values cannot be modified. The class implements the two **amount()** methods.

virtual Real amount() const; virtual Real amount(Real) const;

Both versions of **amount()** return the amount passed to the object in the constructor. The value of an underlying is ignored.

A global utility function lets you quickly create an stl:: vector of fixed dividends from a vector of dates and a vector of amounts.

std::vector<boost::shared_ptr<Dividend> > DividendVector(const std::vector<Date>& dividendDates, const std::vector<Real>& dividends);

This method will construct **FixedDividend** objects and store them in a vector of pointers to dividends. Each date is paired with an amount. The two vector containing the dates and values have to contained the same number of elements, otherwise an exception is thrown.

The **FractionalDividend** implements dividend cash flows that amount to a given fraction of the value of an underlying entity. They can be constructed by specifying the rate and the cash flow date, or by additionally specifying a nominal value of the underlying.

FractionalDividend(Real rate, const Date& date); FractionalDividend(Real rate, Real nominal, const Date& date);

The nominal does not have to be specified if the amount is always calculated using the value of the underlying. Note that, once the object has been created, the object is immutable. In particular, the nominal value cannot be set or changed. The two **amount()** methods are also implemented.

virtual Real amount() const; virtual Real amount(Real underlying) const;

The first version uses the nominal value and returns *rate * nominal*. This version actually implements the **CashFlow** interface. If the nominal value has not been set in the constructor then an exception is thrown. The second version returns* rate * underlying* and ignores the nominal value.

Two inspection methods return the values of the rate and the nominal value respectively.

Real rate() const; Real nominal() const;

In the following code we construct an array of **Dividend** cash flows from data contained in a file and then write out the data.

std::ifstream input("dividends.txt"); int day, month, year; int fixed; Real value; Real rate, nominal; typedef boost::shared_ptr<Dividend> pCashFlow; std::list<pCashFlow> dividends; input >> day >> month >> year >> fixed; while (input) { // convert number into a month Date d = Date(day,January,year) + (month-1)*Months; if (fixed== 1) { input >> value; pCashFlow dividend(new FixedDividend(value, d)); dividends.push_back(dividend); } else { input >> rate >> nominal; pCashFlow dividend(new FractionalDividend(rate, nominal, d)); dividends.push_back(dividend); } input >> day >> month >> year >> fixed; } BOOST_FOREACH(pCashFlow cashFlow, dividends) { std::cout << cashFlow->date() << " " << cashFlow->amount() << std::endl; }

In the example code **Dividend** objects are read from a data file and inserted into a list of **CashFlow** objects. The first three columns in the input file specify the payment date of the dividend. The fourth column is a flag that specifies if the dividend is fixed or fractional. For a fixed dividend only one more value is read and stored in the dividend amount. For fractional dividends twovalues are read from the file and passed to the FractionalDividend as rate and nominal value. After reading the data, all the cash flow amounts are written to the console using a loop over the list. Assume that the file dividends.txt contained the following ficticious data

15 1 2013 0 0.09 100.0 15 4 2013 0 0.10 100.0 15 7 2013 0 0.11 100.0 15 10 2013 1 20.0

This produces the output

January 15th, 2013 9 April 15th, 2013 10 July 15th, 2013 11 October 15th, 2013 20

]]>

Here I will talk about the abstract **TermStrucure** class. In later posts I will talk about the concrete implementations. Term structures need to keep track of a reference date. This reference date can be either fixed to a specific date, it can be given by a fixed number of business days after the evaluation date or it can be linked to the reference date of an underlying structure. Three different constructors are defined for these three cases.

When the reference date is fixed, the following constructor should be used.

TermStructure(const Date& referenceDate, const Calendar& calendar = Calendar(), const DayCounter& dc = DayCounter());

The first argument of this constructor is the reference date, the second argument passes the calendar to the term structure and the third argument is the day counter that is used for calculating the time intervals as fraction of a year. The calendar and day counter default to the default **Calendar** and **DayCounter** classes.

If the reference date is calculated by as fixed offset from today’s date then the following constructor should be used.

TermStructure(Natural settlementDays, const Calendar&, const DayCounter& dc = DayCounter());

The first parameter gives the number of days after the evaluation date. The evaluation date is taken from the global settings, Settings::evaluationDate(). See the discussion of the global settings object for details of how the evaluation date is determined. The second parameter is the calendar used to advance the date forward from the evaluation date. In contrast to the previous constructor, the calendar cannot be left undefined and should be a concrete implementation of the Calendar class. The third parameter is the day counter which is used to calculate time in fractions of a year.

Finally, the constructor which should only be used if the reference date of the term structure depends on some underlying structure.

TermStructure(const DayCounter& dc = DayCounter());

This constructor only has one,optional, parameter, the day counter u as d to calculate fractions of a year. This constructor should only be used for those classes that have re-implemented the **referenceDate()** method to reflect the reference date of the underlying structure.

The central method of the term structure returns the reference date.

virtual const Date& referenceDate() const;

The implementation inside the **TermStrucure** class handles the cases when the reference date is fixed or given as a number of business days after the evaluation date. If other behavior is needed it should be re-implemented in the subclass.

The following methods are utility methods for accessing information about the term structure.

virtual DayCounter dayCounter() const; Time timeFromReference(const Date& date) const; virtual Date maxDate() const = 0; virtual Time maxTime() const; virtual Calendar calendar() const; virtual Natural settlementDays() const; void update();

The method **dayCounter()** returns the day counter associated with the term structure. To access the time between a date and the reference date use the method **timeFromReference()**. The value returned by this function is the time in years as calculated by the day counter. **maxDate()** is an abstract function that should return the maximum date for which the term structure can return values. This method has to be implemented by a concrete term structure. The method maxTime uses the value returned by **maxDate()** and calculates, by calling **timeFromReference()**, the maximum time after the reference date for which values can be returned. The calendar used by the term structure is returned by the **calendar()** method and the method **settlementDays()** returns the number of days between the current evaluation date and the reference date.