【问题标题】:Separating public interface from implementation details将公共接口与实现细节分开
【发布时间】:2011-04-02 19:17:35
【问题描述】:

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

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

编辑:找到这篇关于这个主题的精彩文章:Separating Interface and Implementation in C++

附言我记得在 Objective-C 中,有一些私有类别允许您在私有实现文件中定义类扩展,从而形成非常优雅的解决方案。

【问题讨论】:

    标签: c++


    【解决方案1】:

    您可以使用 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.
    }
    

    【讨论】:

    • pimpl 的伟大之处在于实现类可以是多态的(这在设计模式宗教 iirc 中有一个名字)。所以事实上,你可以使用工厂,如果需要,你也可以在运行时选择一个实现(以适应例如操作系统变体)。
    猜你喜欢
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    • 2013-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    相关资源
    最近更新 更多