Singleton Pattern in Quantlib

Ok, the Singleton pattern is one of the easiest patters in QuantLib, so I will start with that one first. A Singleton pattern guarantees that only one instance of an object will be needed in a system or framework like Quantlib. The Singleton pattern is usually implemented as a class that returns an instance of the object if one exists, or creates one if it does not exist. To make sure that the object cannot be instantiated any other way, the constructor is made protected .

So here is the simple version of the Singleton class in QuantLib


template
class Singleton : private boost::noncopyable {
public:
static T& instance();
protected:
Singleton() {}
};

In QuantLib, it is implemented as a template, which makes life easier. We don’t want to have to write the same thing for each singleton class. The Singleton class is the base class for four other classes

ExchangeRateManager - exchange-rate repository
IndexManager - global repository for past index fixings
SeedGenerator - Random seed generator.
Settings - global repository for run-time library settings

You may have noticed the boost::noncopyable. This is from the Boost libs, and it makes the copy constructor and copy assignment private to ensure classes derived from class noncopyable cannot be copied. So we cannot copy a Singleton.

So when we want to get an instance of the object, we call the method instance


mt19937uniformrng.cpp: unsigned long s = (seed != 0 ? seed : SeedGenerator::instance().get());

So lets look at an example usage in Quantlib. mt19937uniformrng.cpp is a Seed generator. The call to the method unsigned long get () returns the Random seed. SeedGenerator::instance() returns the instance , and the get() method returns the Random seed.

We all know what a Singleton is. A lot of people do not like the Singleton pattern as they feel it is a warm fuzzy throwback to Non OOP programming. Like a global variable. But that is life, and the Singleton pattern is useful.

There are some things I did not cover for sake of incompleteness like QL_ENABLE_SESSIONS, but I leave that for later.

Share and Enjoy:
  • del.icio.us
  • digg
  • Reddit