对于静态 C++ 库的某些类,我想为库的用户和库本身提供不同的接口。
一个例子:
class Algorithm {
public:
// method for the user of the library
void compute(const Data& data, Result& result) const;
// method that I use only from other classes of the library
// that I would like to hide from the external interface
void setSecretParam(double aParam);
private:
double m_Param;
}
我的第一次尝试是将外部接口创建为 ABC:
class Algorithm {
public:
// factory method that creates instances of AlgorithmPrivate
static Algorithm* create();
virtual void compute(const Data& data, Result& result) const = 0;
}
class AlgorithmPrivate : public Algorithm {
public:
void compute(const Data& data, Result& result) const;
void setSecretParam(double aParam);
private:
double m_Param;
}
优点:
- 算法的用户看不到内部界面
缺点:
- 用户必须使用工厂方法来创建实例
- 当我想从库内部访问秘密参数时,我必须将 Algorithm 向下转换为 AlgorithmPrivate。
我希望你能理解我试图达到的目标,我期待着任何建议。