我必须设计一个 Font
类,该类将具有跨平台或不同库(例如 Win32 GDI 或 FreeType)的多个实现。所以基本上会有单个共享头文件/接口(interface)文件和多个 .cpp 实现(在构建时选择)。我宁愿保持公共(public)接口(interface)(头文件)不受任何实现细节的影响,但这通常很难实现。字体对象必须拖动某种私有(private)状态 - 如 GDI 中的句柄,或内部的 FreeType 面部对象。
在 C++ 中,跟踪私有(private)实现细节的最佳方法是什么?我应该在实现文件中使用静态数据吗?
编辑: 发现这篇关于该主题的精彩文章:Separating Interface and Implementation in C++ .
附注我记得在 Objective-C 中有私有(private)类别,允许您在私有(private)实现文件中定义类扩展,从而形成非常优雅的解决方案。
最佳答案
您可以使用 PIMPL 设计模式。
这基本上是您的对象持有指向实际平台相关部分的指针并将所有平台相关调用传递给该对象的地方。
字体.h
class FontPlatform;
class Font
{
public:
Font();
void Stuff();
void StuffPlatform();
private:
FontPlatform* plat;
};
字体.cpp
#include "Font.h"
#if Win
#include "FontWindows.h"
#else
#error "Not implemented on non Win platforms"
#endif
Font::Font()
: plat(new PLATFORM_SPCIFIC_FONT) // DO this cleaner by using factory.
{}
void Font::Stuff() { /* DoStuff */ }
void Font::StuffPlatform()
{
plat->doStuffPlat(); // Call the platform specific code.
}
关于c++ - 将公共(public)接口(interface)与实现细节分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5522626/