2017-03-16 124 views
0

您是否有任何關於在C++中實現硬件抽象層的設計模式或技術的建議,以便我可以在構建時輕鬆切換平臺?我正在考慮使用類似我在GoF或C++模板中閱讀的橋模式,但我不確定這是否是最佳選擇。C++中用於HAL實現的設計模式

回答

1

我認爲在構建時使用橋接模式並不是一個好的選擇。

這是我的解決方案:

定義一個標準設備類作爲接口:

class Device { 
    ... // Common functions 
}; 

對於X86平臺:

#ifdef X86 // X86 just is an example, user should find the platform define. 
class X86Device: public Device{ 
    ... // special code for X86 platform 
}; 
#endif 

對於ARM平臺:

#ifdef ARM // ARM just is an example, user should find the platform define. 
class ARMDevice: public Device { 
    ... // Special code for ARM platform 
}; 
#endif 

使用t HESE設備:

#ifdef X86 
Device* dev = new X86Device(); 
#elif ARM 
Device* dev = new ARMDevice(); 
#endif 

編譯選項:

$ g++ -DARM ... // using ArmDevice 
$ g++ -DX86 ... // using X86Device 
+4

如果無論如何你知道編譯時的目標CPU,爲什麼訴諸動態多態?你從每一方都輸了! –

+0

同意!另外,SFINAE over #ifdef – Jeff

+0

X86和ARM只是一個例子,你可以用PAX255,IT3354來代替它們。對於一個設備來說,不同平臺的驅動程序的源代碼除了一些關鍵點之外幾乎與初始化過程相同。我可以將所有這些代碼寫入一個類或文件中的不同平臺,但在代碼維護@DavidHaim – netdigger