【发布时间】:2014-08-28 01:18:49
【问题描述】:
我正在使用 C++ 编写一个简单的 API,在该 API 中,我的代码的最终用户会将 UserProfile 类的实例传递给其他各种类进行修改。用户配置文件有一个非常基本的公共接口,数据存储在一个私有 pimpl 对象中。然后我将实现类添加为朋友,以便他们可以访问在单独的实现文件中定义的内部数据结构。此类的基本大纲如下所示。 . .
// For pimpl here
class UserProfileData;
class UserProfile
{
public:
/// ctor to allocate impl
UserProfile();
/// dtor
~UserProfile();
/// Do some very simple stuff with a few methods
std::string getProfileName() const;
private:
/// Use pimpl and hide impl so API user can just use simplified interface
std::unique_ptr<UserProfileData> userProfileData;
/// Allow implementation classes access to userProfileData
friend class ClassOne;
friend class ClassTwo;
};
构建一个庞大的朋友类列表并不是向 API 用户隐藏数据的最优雅的解决方案。好像有点臭。是否有任何模式或习语可以让我以不同的方式实现相同的目标?
【问题讨论】:
-
大多数时候,
ClassOne或ClassTwo需要的任何东西都应该是public。您自己就是您的 API 的用户。 -
这里没有足够的细节来选择各种选项。例如,为什么不只为 userProfileData 提供一个公共访问器函数,而只为不应访问的人保留未定义的 UserProfileData 呢?你想阻止什么用例?
标签: c++ design-patterns architecture idioms