我想用C++设计一个包装类,使用FTP、SFTP实现文件传输。
我有一个基类FileTransfer
(使用curl),它由派生类FTP
继承。我需要支持 SFTP,因此我实现了另一个派生类 SFTP
,它也继承自 FileTransfer
。
我正在按照以下几行制作包装类代码。然而,这看起来并不是一个好的设计。尽管我过去曾从事过 C 工作,但我对 OOP 还比较陌生。
class Wrapper {
public:
Wrapper(int m_protocol){
protocol = m_protocol;
if (protocol)
pftp = new FTP();
else
psftp = new SFTP();
}
~Wrapper() {
if (protocol)
delete pftp;
else
delete psftp;
}
//Function supported by both ftp/sftp
void do_something(){
if (protocol)
pftp->do_something();
else
psftp->do_something();
}
//FTP specific function
void use_passive(){
assert(protocol);
pftp->use_passive();
}
//SFTP specific function
void ssh_key(){
assert(!protocol);
psftp->ssh_key();
}
private:
int protocol;
FTP *pftp;
SFTP *psftp;
};
我该如何改进这个设计?如何避免每个函数内部的 if (protocol)
检查并提高代码质量?我应该为 psftp
和 'pftp` 使用 void
指针吗?
编辑:我正在使用包装器,因为在项目中的很多地方,正在使用现有的 FTP 对象,如果我为 SFTP 使用单独的类(没有包装器),我将必须添加一个 if
每次都检查是否也支持 SFTP。我不想向调用者公开详细信息 (FTP/SFTP)。
最佳答案
只需使用基类指针即可轻松完成这里的所有操作。
FileTransfer* ft;
std::unique_ptr<FileTransfer> ft; // C++11
制作一个:
// should this really be an int?
FileTransfer* factory(int protocol) {
if (protocol)
return new FTP;
else
return new SFTP;
}
// in C++11 this should be
std::unique_ptr<FileTransfer> factory(int protocol);
做某事:
ft->do_something();
做一些特定于其中一个或另一个的事情:
// this will die if ft is an SFTP
dynamic_cast<FTP*>(ft)->use_passive();
// but you could check it
if (FTP* ftp = dynamic_cast<FTP*>(ft)) {
ftp->use_passive();
}
// or perhaps even better, make a default virtual that does nothing
virtual void FileTransfer::use_passive() { }
void FTP::use_passive() override { // whatever }
ft->use_passive();
删除:
// make sure FileTransfer::~FileTransfer() is virtual!!
delete ft;
关于c++ - 设计一个好的 C++ 包装类来包装多种功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26690901/