對於某些類的靜態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;
}
優點:
- 算法的用戶無法看到內部接口
缺點:
- 用戶必須使用工廠方法創建實例
- 我不得不垂頭喪氣算法對AlgorithmPrivate當我想從庫中訪問機密參數。
我希望你明白我想達到的目標,我期待着任何建議。
如果不加破壞方法需要算法的虛擬析構函數。但我沒有看到你的問題。 – Totonga 2010-02-25 08:46:26
爲了簡單起見,我省略了構造函數和析構函數,當然算法需要一個虛擬析構函數。問題在於是否有比我更優雅的解決方案,可以將一個班級的成員打開到其他班級,同時將他們從「外部」隱藏起來。 – Stephan 2010-02-25 11:20:34