fork download
  1. #include <memory>
  2. #include <iostream>
  3.  
  4. struct ABC {
  5. virtual ~ABC(){}
  6. virtual int getValue() const { return 42; }
  7. };
  8.  
  9. struct DerivedABC : ABC {
  10. int getValue() const override { return -1; }
  11. };
  12.  
  13. class XYZFactory {
  14. public:
  15. virtual ~XYZFactory(){}
  16. virtual std::unique_ptr<ABC> createABC() const = 0;
  17. };
  18.  
  19. class XYZFactoryImpl : public XYZFactory {
  20. public:
  21. std::unique_ptr<ABC> createABC() const override {
  22. return std::make_unique<ABC>();
  23. }
  24. };
  25.  
  26. class ExtendedXYZFactoryImpl : public XYZFactory {
  27. public:
  28. std::unique_ptr<ABC> createABC() const override {
  29. return std::make_unique<DerivedABC>();
  30. }
  31. };
  32.  
  33. namespace details { // Or hide this in an anonymous namespace in a .cpp file.
  34. std::unique_ptr<XYZFactory>& getXYZFactoryInstanceMutable() {
  35. static std::unique_ptr<XYZFactory> singleton = std::make_unique<XYZFactoryImpl>();
  36. return singleton;
  37. }
  38. }
  39.  
  40. const XYZFactory& getXYZFactoryInstance() {
  41. auto& singleton = details::getXYZFactoryInstanceMutable();
  42. if (!singleton)
  43. throw std::runtime_error("No XYZFactory registered");
  44. return *singleton;
  45. }
  46.  
  47. void setXYZFactoryInstance(std::unique_ptr<XYZFactory> new_factory) {
  48. details::getXYZFactoryInstanceMutable() = std::move(new_factory);
  49. }
  50.  
  51. int main() {
  52. auto abc = getXYZFactoryInstance().createABC();
  53. std::cout << abc->getValue() << "\n";
  54.  
  55. setXYZFactoryInstance(std::make_unique<ExtendedXYZFactoryImpl>());
  56.  
  57. auto extended_abc = getXYZFactoryInstance().createABC();
  58. std::cout << extended_abc->getValue() << "\n";
  59. }
  60.  
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
42
-1