平時口頭上說的“Adapter Pattern”是指,庫代碼與實際應用端的功能需求不一致,但確實存在一部分的庫代碼可以重用,于是把庫代碼適配成所需的功能接口,于是“生出”一個適配器類,給某一個/或多個庫中的作了一次功能包裝,順便補上沒有的功能,所以,往往有如下這樣的code:

// windowInterface是庫的接口類,window_win32/window_qt/window_gtk是庫中的實現類的情況下

class MyWindowAdaptor: public windowInterface, protected window_win32
{
public:
???//一些所需的接口函數...

? void resize(int x, int y) {???// eg.
??????// ...
??????window_win32::resize(x,y);
???}
};
或是
class MyWindowAdaptor: public windowInterface{
public:
???//一些所需的接口函數...

? void resize(int x, int y) {???// eg.
??????// ...
??????winImpl_.resize(x,y);
???}
private:
? window_win32 winImpl_;
};

而pixeltoastor里面使用了一丁點的宏,完成了類似的事情,并且由此得到了平臺可移植性,把平臺相關的實現代碼約束在編譯期,使得用戶代碼更為clear,大致的輪廓如下:

// window interface
struct WindowAdaptor {
? virtual ~WindowAdaptor() {}

? virtual void set(int ) =0;
? virtual int get() =0;
? virtual void update() =0;
? virtual void resize(int , int ) =0;
};

// device interface
struct GraphicAdaptor {
? virtual ~GraphicAdaptor() {}

? virtual bool beginScene() =0;
? virtual void endScene() =0;
? virtual void clearScene() =0;

? virtual void drawTriangle(Tri* pStart, unsigned count) =0;
};

?


// platform config macro
#ifdef WIN32
# define USE_OGL
# define USE_DX9
#elif LINUX
# define USE_OGL
#endif


// window implement
#ifdef WIN32
class Window_win32: public WindowAdaptor {
public:
? virtual ~Window_win32() {}

? virtual void set(int )
? { }

? virtual int get()
? { return 0; }

? virtual void update()
? { }

? virtual void resize(int , int )
? { }

? // ...
};
#define Window Window_win32
#endif

#ifdef LINUX
class Window_Linux: public WindowAdaptor {
? // implement code...
};
#define Window Window_Linux
#endif

// device implement
#ifdef USE_DX9
class GraphicDevice_Dx9: public GraphicAdaptor {
? // implement code...
};
#define GraphicDx9 GraphicDevice_Dx9
#endif

#ifdef USE_OGL
class GraphicDevice_OGL: public GraphicAdaptor {
? // implement code...
};
#define GraphicOGL GraphicDevice_OGL
#endif

?

/*? --------------------user code------------------------
// Display
class Display: public Window, public GraphicDx9 {
};

int main()
{
? Display disp;
? //...

? return 0;
}
*/

以上只是表示了邏輯結構,同時其物理結構也想象的出了!
這里保證了類型安全,不失靈活性與健壯性,卻引入了可以接受的隱含的名稱沖突,像這樣的idom可以應用到與具體平臺或設備相關的programming任務上,如:音頻處理模塊、輸入設備模塊。

{?Message("新春愉快!", "^o^"); }