Library design: Hiding dependencies

后端 未结 1 1458
自闭症患者
自闭症患者 2021-02-10 14:37

I\'m attempting to build a library that uses a third-party library internally, but I do not want to expose and of this third-party library to the user of my library. This way, w

1条回答
  •  太阳男子
    2021-02-10 15:18

    The "private implementation class" or "pimpl" idiom is one approach. This keeps all mention of the third-party library (and other implementation details) out of the header, at the cost of an extra level of indirection:

    // header
    #include 
    
    class DummyClass {
    public:
        DummyClass();
        ~DummyClass();
        bool checkStuff(float t);
    
    private:
        struct Impl;
        std::unique_ptr impl;
    };
    
    // source
    #include "DummyClass.h"
    #include "ThirdPartyLib.h"
    
    struct DummyClass::Impl {
        TypeFromThirdParty tftp;
    };
    
    DummyClass::DummyClass() : impl(new Impl) {}
    
    // This must be defined here, since ~unique_ptr requires Impl to be complete
    DummyClass::~DummyClass() {}
    
    bool DummyClass::checkStuff(float t) {return impl->tftp.isOk(t);}
    

    Another approach is to define an abstract interface, and a factory to create the concrete implementation class. Again, this removes all implementation details from the header, at the cost of an extra indirection:

    // header
    #include 
    
    struct DummyInterface {
        virtual ~DummyInterface() {}
        virtual bool checkStuff(float t) = 0;
    
        static std::unique_ptr create();
    };
    
    // source
    #include "DummyClass.h"
    #include "ThirdPartyLib.h"
    
    struct DummyClass : DummyInterface {
        TypeFromThirdParty tftp;
        bool checkStuff(float t) {return tftp.isOk(t);}
    };
    
    std::unique_ptr DummyInterface::create() {
        return std::unique_ptr(new DummyClass);
    }
    

    0 讨论(0)
提交回复
热议问题