对于静态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;
}
优点:
缺点:
我希望你理解我想要达到的目标,我期待着任何建议。
答案 0 :(得分:3)
最简单的方法可能是setSecretParam()
private
并将friend
Algorithm
作为void setSecretParam(Algorithm& algorithm, double aParam)
{
void setSecretParam(double aParam);
}
:
{{1}}
答案 1 :(得分:1)
替换继承的“通常嫌疑人”是Bridge pattern。您可以定义从抽象类AlgorithmImp派生的“Imps”层次结构,并且只在库头中公开适当的算法。然后可以创建算法实例
ConcreteAlgorithm ca1(SomeParam, new LibraryUserAlgorithm());
ConcreteAlgorithm ca2(SomeParam, new InternalAlgorithm());