我正在尝试编写一个抽象层,让我的代码可以在不同的平台上运行。让我举个例子,这里有两个类,我最终希望在高级别代码中使用:
class Thread
{
public:
Thread();
virtual ~Thread();
void start();
void stop();
virtual void callback() = 0;
};
class Display
{
public:
static void drawText(const char* text);
};
我的问题是:我可以使用什么设计模式让低级别的代码填写实现?以下是我的想法以及为什么我认为它们不是一个好的解决方案:
In theory there's no problem in having the above definition sit in
highLevel/thread.h
and the platform specific implementation sit inlowLevel/platformA/thread.cpp
. This is a low-overhead solution that is resolved at link-time. The only problem is that the low level implementation can't add any member variables or member functions to it. This makes certain things impossible to implement.A way out would be to add this to the definition (basically the Pimpl-Idiom):
class Thread { // ... private: void* impl_data; }
Now the low level code can have it's own struct or objects stored in the void pointer. The trouble here is that its ugly to read and painful to program.
I could make
class Thread
pure virtual and implement the low level functionality by inheriting from it. The high level code could access the low level implementation by calling a factory function like this:// thread.h, below the pure virtual class definition extern "C" void* makeNewThread(); // in lowlevel/platformA/thread.h class ThreadImpl: public Thread { ... }; // in lowLevel/platformA/thread.cpp extern "C" void* makeNewThread() { return new ThreadImpl(); }
This would be tidy enough but it fails for static classes. My abstraction layer will be used for hardware and IO things and I would really like to be able to have
Display::drawText(...)
instead of carrying around pointers to a singleDisplay
class.Another option is to use only C-style functions that can be resolved at link time like this
extern "C" handle_t createThread()
. This is easy and great for accessing low level hardware that is there only once (like a display). But for anything that can be there multiple times (locks, threads, memory management) I have to carry around handles in my high level code which is ugly or have a high level wrapper class that hides the handles. Either way I have the overhead of having to associate the handles with the respective functionality on both the high level and the low level side.My last thought is a hybrid structure. Pure C-style
extern "C"
functions for low level stuff that is there only once. Factory functions (see 3.) for stuff that can be there multiple times. But I fear that something hybrid will lead to inconsistent, unreadable code.
我希望能得到一些适合我的需求的设计模式提示。