为类/信息隐藏创建内部和外部接口
对于静态 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从库内部访问秘密参数。
我希望您理解我想要实现的目标,并期待任何建议。
For some classes of a static C++ library I want to offer different interfaces for the user of the library and for the library itself.
An example:
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;
}
My first attempt was to create the external interface as an 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;
}
Pros:
- The user of Algorithm cannot see the internal interface
Cons:
- The user has to use a factory method to create instances
- I have to downcast Algorithm to AlgorithmPrivate when I want to access the secret parameters from inside the library.
I hope you understand what I try to achieve and I'm looking forward to any suggestions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单的方法可能是使
setSecretParam()
private
并使以下内容成为Algorithm
的friend
:The simplest way might be to make
setSecretParam()
private
and make the following afriend
ofAlgorithm
:替换继承的“通常嫌疑人”是桥接模式。您可以定义从抽象类 AlgorithmImp 派生的“Imps”层次结构,并且仅在库标头中公开适当的算法。然后可以创建一个算法实例:
The "usual suspect" to replace inheritance is Bridge pattern. You could define an hierarchy of "Imps" derived from abstract class AlgorithmImp and only expose appropriate algorithms in the library headers. Then an instance of algorithm can be created as