我开发了一个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