我开发了一个可以在两个不同平台上运行的Java库。要打印消息,一个平台使用printA(str)
方法,而另一个平台使用printB(str)
方法。在C ++中,我创建了一个静态方法:
public static void print(string str)
{
#ifdef platformA
printA(str);
#else
printB(str);
#endif
}
由于Java没有#ifdef
,因此它变得棘手。我开始用静态方法查看覆盖抽象类,但不确定我是否正确方向。最优雅的方式是什么?
编辑:回答Andy Thomas(谢谢!)我找到了适合我的解决方案。唯一的缺点 - 它必须在启动时初始化。下面是代码。 公共图书馆:
//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!");
}
}
答案 0 :(得分:1)
使用常量表达式:
private static final boolean PLATFORM_A = true;
public static void print(string str)
{
if(PLATFORM_A )
{
printA(str);
}
else
{
printB(str);
}
}
答案 1 :(得分:1)
这段代码怎么样?
public class Example {
public static void main(String[] args) {
print();
}
public static void print() {
String platform = System.getProperty("os.name");
switch (platform) {
case "Windows 7":
System.out.println("This is Windows 7");
break;
case "Windows XP":
System.out.println("This is Windows XP");
break;
}
}
}
答案 2 :(得分:0)
您可以使用strategy pattern。
定义一次接口,并在特定于操作系统的类中实现它。
public interface IPlatformAPI {
public void print( String str );
}
public class WindowsPlatformAPI implements IPlatformAPI {
public void print( String str ) { ... }
}
public class MacPlatformAPI implements IPlatformAPI {
public void print( String str ) { ... }
}
public class LinuxPlatformAPI implements IPlatformAPI {
public void print( String str ) { ... }
}
public class PlatformAPI {
public static IPlatformAPI getPlatformAPI() {
// return one of the platform APIs
// You can use System.getProperty("os.name") to choose the implementation
}
}