包装类设计和依赖注入

问题描述 投票:0回答:1

我有一个简单的FTP类,负责通过cURL库下载和上传:

class FTPClient
{
public:
    explicit FTPClient(const std::string& strIPAddress);
    virtual ~FTPClient();

    bool DownloadFile(const std::string& strRemoteFile, const std::string& strLocalFile);
    bool UploadFile(const std::string& strLocalFile, const std::string& strRemoteFile);

private:
    static size_t WriteToFileCallBack(void *ptr, size_t size, size_t nmemb, FILE *stream);
    static size_t ReadFromFileCallback(void* ptr, size_t size, size_t nmemb, FILE *stream);

    std::string m_strUser;
    std::string m_strPass;
    std::string m_strIPAddress;
    std::string m_strPort;

    mutable CURL* m_objCurlSession;
};

我已经询问了一些关于如何实现和构建更好的建议,因为它是项目的基础和核心,并且它将在许多部分中使用。我被告知使用cURLWrapper类来包装所有cURL调用(curl_easy_setopt(..)),但后来我被告知要为FTP类创建一个接口,一个只调用FTP方法的cURLWrapper然后是一个具体的类...但是它对我来说太抽象了,并且不了解实现它的最佳方式以及遵循的路径。

你会如何接近这个小结构?

c++ oop wrapper
1个回答
0
投票

为FTP类定义一个简单的接口:

class IFTPClient
{
public:
    virtual ~IFTPClient();

    virtual bool DownloadFile(const std::string& strRemoteFile, const std::string& strLocalFile) = 0;
    virtual bool UploadFile(const std::string& strLocalFile, const std::string& strRemoteFile) = 0;
};

我假设您的静态回调方法正在调用某个类实例而不是单个实例?那很好。从界面中派生您的类:

class FTPClient:IFTPClient
{
    ...

我注意到您将IP地址传递给构造函数,并在其他地方定义了其他参数(用户名,密码,端口等)。那似乎并不十分一致。您需要重构它,以便可以通过接口方法设置这些参数或将这些参数添加到上载/下载方法。

在其他地方需要之前构造你的FTPClient对象,然后只将接口传递(“注入”)到想要使用FTPClient的对象。对于不使用实际FTPClient的单元测试,构造一个从同一接口派生的模拟对象,并将其注入其他对象。

其他对象只是使用界面中公开的功能,不需要知道或担心其内部实现;如果你决定使用curl或其他东西,那么完全取决于FTPClient

简而言之就是这样;你可能想在互联网上搜索依赖注入和框架,但你不需要一个框架来遵循依赖注入原则,在我看来,它们对于简单的项目来说可能是过度的。

© www.soinside.com 2019 - 2024. All rights reserved.