Exercise: Singleton (Flexible)

In certain scenarios, it might be advisable to be more flexible. In our hypothetic single social insurance world, this could for example mean that we might want to exchange the implementation of the insurance with one that adds a fee of 10% to every charge.

Modify your solution to Exercise: Singleton (Inflexible):

  • Create a social insurance interface SocialInsurance

  • Create a SVS implementation of that interface. That particular implementation is the one that adds a 10% fee.

  • Create an OEGK implementation that does not add a fee.

Add the following program to your build system. The program uses the two implementations.

#include "social-insurance-svs.h"
#include "social-insurance-oegk.h"

#include <iostream>
#include <string>
#include <memory>


int main()
{
    // setup phase, next to program startup
    SocialInsurance::set_instance(std::make_unique<SVS>());

    std::string id("1037190666");

    SocialInsurance::instance().charge(id, 1254.60);
    SocialInsurance::instance().charge(id, 231.34);
    
    std::cout << id << " owes \"" << SocialInsurance::instance().name() << "\" " << SocialInsurance::instance().debt(id) << " Euros" << std::endl;

    // can only be a runtime error: trying to overwrite singleton
    // instance
    SocialInsurance::set_instance(std::make_unique<OEGK>());

    return 0;
}

When run, the program outputs the following (and crashes):

$ ./singleton-social-insurance-flexible-main
1037190666 owes "SVS" 1634.53 Euros
terminate called after throwing an instance of 'std::runtime_error'
  what():  SocialInsurance singleton already in place
Aborted (core dumped)