Separating public interface from implementation details
I have to design a Font
class that will have multiple implementations spanning platforms or different libraries (Win32 GDI or FreeType for example). So essentially there will be single shared header/interface file and multiple .cpp implementations (selected during build time). I would prefer to keep the public interface (header file) cle开发者_如何学Can from any implementation details, but this usually is hard to achieve. A font object has to drag some sort of a private state - like a handle in GDI, or FreeType face object internally.
In C++, what is the best way to track private implementation details? Should I use static data in implementation files?
Edit: Found this great article on the subject: Separating Interface and Implementation in C++.
p.s. I recall in Objective-C there are private categories that allow you to define a class extension in your private implementation file making quite elegant solution.
You can use the PIMPL design pattern.
This is basically where your object holds a pointer to the actual platform dependent part and passes all platform dependent calls through to this object.
Font.h
class FontPlatform;
class Font
{
public:
Font();
void Stuff();
void StuffPlatform();
private:
FontPlatform* plat;
};
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.
}
精彩评论