Any suggestions on how the implementation of the C++ Adapter pattern could be improved here? Implemented via:
- Composition
- Inheritance
What needed to be adapted was the OptionLegacy
class which returns implied volatility of the option but the client needs the dollar price so a simple conversion was included.
#include <iostream>
#include <cmath>
// Return price of option by volatility
// Adaptee - old legacy type option objects
class OptionLegacy
{
protected:
float volatilityPrc;
double spotPrice;
int expiryDays;
public:
OptionLegacy(float v, double s, int t) :
volatilityPrc(v), spotPrice(s), expiryDays(t) {}
float GetVol() const {
return volatilityPrc;
}
double GetSpot() const {
return spotPrice;
}
int GetTau() const {
return expiryDays;
}
};
// Return price of option in dollars. Current interface that client uses
class OptionPriceDollars
{
protected:
float vol;
double spot;
double tau;
public:
OptionPriceDollars() = default;
OptionPriceDollars(float v, double s, double t) :
vol(v), spot(s), tau(t) {}
virtual float GetPrice() {
return 0.4 * spot * vol * sqrt(tau);
}
};
// via composition
class Adapter
{
OptionLegacy adaptee;
public:
Adapter(const OptionLegacy & o): adaptee(o) {}
float GetPrice() {
return 0.4 * adaptee.GetSpot() * adaptee.GetVol() / 100 * sqrt(adaptee.GetTau()/365);
}
};
// via inheritance
class AdapterInheritance : public OptionPriceDollars, private OptionLegacy
{
public:
AdapterInheritance(const OptionLegacy & o) : OptionLegacy(o.GetVol(), o.GetSpot(), o.GetTau()) {};
float GetPrice() override {
return 0.4 * spotPrice * volatilityPrc / 100 * expiryDays / 365;
}
};
int main()
{
OptionPriceDollars od(0.14, 100, 1);
std::cout << "The price of the option is " << od.GetPrice() << std::endl;
OptionLegacy op(14, 100, 365);
Adapter a(op);
std::cout << "The price of the old style option is (composition) " << a.GetPrice() << std::endl;
AdapterInheritance b(op);
std::cout << "The price of the old style option is (inheritance) " << b.GetPrice() << std::endl;
int x;
std::cin >> x;
}