Library design: Hiding dependencies

£可爱£侵袭症+ 提交于 2019-12-03 08:39:14

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 <memory>

class DummyClass {
public:
    DummyClass();
    ~DummyClass();
    bool checkStuff(float t);

private:
    struct Impl;
    std::unique_ptr<Impl> 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 <memory>

struct DummyInterface {
    virtual ~DummyInterface() {}
    virtual bool checkStuff(float t) = 0;

    static std::unique_ptr<DummyInterface> 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> DummyInterface::create() {
    return std::unique_ptr<DummyInterface>(new DummyClass);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!