将公共接口与实现细节分开

Sim*_*Sim 5 c++

我必须设计一个Font具有跨平台或不同库(例如Win32 GDI或FreeType)的多个实现的类.所以基本上会有单个共享头/接口文件和多个.cpp实现(在构建时选择).我宁愿保持公共接口(头文件)清除任何实现细节,但这通常很难实现.字体对象必须拖动某种私有状态 - 如GDI中的句柄或内部的FreeType面对象.

C++中,跟踪私有实现细节的最佳方法是什么?我应该在实现文件中使用静态数据吗?

编辑:发现这篇关于这个主题的好文章:用C++分离接口和实现.

ps我记得在Objective-C中有一些私有类,它们允许你在私有实现文件中定义类扩展,从而制作出非常优雅的解决方案.

Mar*_*ork 7

您可以使用PIMPL设计模式.

这基本上是您的对象拥有指向实际平台相关部分的指针并将所有平台相关调用传递给此对象的位置.

Font.h

class FontPlatform;
class Font
{
   public:
       Font();
       void Stuff();
       void StuffPlatform();
   private:
       FontPlatform*  plat;
};
Run Code Online (Sandbox Code Playgroud)

Font.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.
}
Run Code Online (Sandbox Code Playgroud)