平時(shí)口頭上說的“Adapter Pattern”是指,庫代碼與實(shí)際應(yīng)用端的功能需求不一致,但確實(shí)存在一部分的庫代碼可以重用,于是把庫代碼適配成所需的功能接口,于是“生出”一個(gè)適配器類,給某一個(gè)/或多個(gè)庫中的作了一次功能包裝,順便補(bǔ)上沒有的功能,所以,往往有如下這樣的code:
// windowInterface是庫的接口類,window_win32/window_qt/window_gtk是庫中的實(shí)現(xiàn)類的情況下
class MyWindowAdaptor: public windowInterface, protected window_win32
{
public:
???//一些所需的接口函數(shù)...
? void resize(int x, int y) {???// eg.
??????// ...
??????window_win32::resize(x,y);
???}
};
或是
class MyWindowAdaptor: public windowInterface{
public:
???//一些所需的接口函數(shù)...
? void resize(int x, int y) {???// eg.
??????// ...
??????winImpl_.resize(x,y);
???}
private:
? window_win32 winImpl_;
};
而pixeltoastor里面使用了一丁點(diǎn)的宏,完成了類似的事情,并且由此得到了平臺(tái)可移植性,把平臺(tái)相關(guān)的實(shí)現(xiàn)代碼約束在編譯期,使得用戶代碼更為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;
}
*/
以上只是表示了邏輯結(jié)構(gòu),同時(shí)其物理結(jié)構(gòu)也想象的出了!
這里保證了類型安全,不失靈活性與健壯性,卻引入了可以接受的隱含的名稱沖突,像這樣的idom可以應(yīng)用到與具體平臺(tái)或設(shè)備相關(guān)的programming任務(wù)上,如:音頻處理模塊、輸入設(shè)備模塊。
{?Message("新春愉快!", "^o^"); }