I have been working through "C++ Design Patterns and Derivatives Pricing" by Mark Joshi. In chapter 4 the Parameters
class uses a bridge pattern and employs a clone()
method.
The justification of the pattern mentions that it allows the extension of the parameters class by inheriting from ParametersInner
and providing that class with virtual
clone()
, Integral(double time1, double time2)
, and IntegralSquare(double time1, double time2)
methods.
I can however acheive the same with simple inherritance. I can also avoid having to use the clone method by using std::make_unique
outside of the class.
My version of this is as follows. (I use a curve
class instead of a parameters
class)
#include <vector>
#include <memory>
class curve
{
public:
virtual double Integral(double time1, double time2) const = 0;
virtual double IntegralSquare(double time1, double time2) const = 0;
virtual double Mean(double time1, double time2) const {
return Integral(time1, time2) / (time2 - time1);
}
virtual double RootMeanSquare(double time1, double time2) const {
return IntegralSquare(time1, time2) / (time2 - time1);
}
};
class constant_curve : curve
{
public:
constant_curve() = default;
constant_curve(const constant_curve &) = default;
constant_curve & operator=(const constant_curve &) = default;
constant_curve(double value):
m_val{value}
{}
virtual double Integral(double time1, double time2) const override{
return (time2 - time1)*m_val;
}
virtual double IntegralSquare(double time1, double time2) const override{
return (time2 - time1)*m_val*m_val;
}
private:
double m_val;
};
int main()
{
std::vector<std::unique_ptr<curve>> curves;
curves.emplace_back(std::make_unique<constant_curve>(10));
}
My Question is this:
What are the reasons to use the bridge pattern as used in the book as apposed to the more simple pattern above?
I am not sure if I am allowed to copy the code to this forum, so here is a link to the code. Design Patterns and Derivatives Pricing 2nd Edition.