我開發了一個Java庫,它將在兩個不同的平臺上運行。要打印消息,一個平臺使用printA(str)
方法,而另一個使用printB(str)
方法。在C++中,我想創建一個靜態方法:Java依賴於平臺的類繼承
public static void print(string str)
{
#ifdef platformA
printA(str);
#else
printB(str);
#endif
}
由於Java沒有#ifdef
,就成了一個棘手的任務。我開始考慮用靜態方法重寫抽象類,但不確定我是否朝着正確的方向前進。什麼是最優雅的方式來做到這一點?
編輯:(!感謝)和安迪·托馬斯的答案,我發現適合我的解決方案。唯一的缺點 - 它必須在啓動時初始化。以下是代碼。 公共庫:
//interface is only for internal use in Output class
public interface IPrintApi
{
public void Print(String message);
}
public abstract class Output
{
private static IPrintApi m_api;
public static void SetPrintAPI(IPrintApi api)
{
m_api=api;
}
public static void MyPrint(String message)
{
m_api.Print(message);
}
}
此功能的呼叫是在公共庫和特定於平臺的代碼相同:
public class CommonTest
{
public CommonTest()
{
Output.MyPrint("print from library");
}
}
代碼爲每個平臺都必須有特定於平臺實現的接口,例如中platformA(對於B是相同的):
public class OutputA implements IPrintApi
{
public void Print(String message)
{
//here is our platform-specific call
PrintA(message);
}
}
用法:
public class AppPlatformA
{
public static void main(String[] args)
{
// point the abstract Output.Print function to the available implementation
OutputA myPrintImpl = new OutputA();
Output.SetPrintAPI(myPrintImpl);
// and now you can use it!
Output.MyPrint("hello world!");
}
}
[http://stackoverflow.com/questions/228477/how-do-i-programmatically-determine-operating-system-in-java][1] 我認爲這可以幫助你。 – nikoliazekter 2014-10-30 16:16:35
這不是一個運行時檢測的問題,它更多的是避免編譯時問題的代碼設計:printA在我使用platformB庫時沒有定義,反之亦然... – 2014-10-30 17:19:46