Java平台相关类继承



我开发了一个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");
    }
}

每个平台的代码必须具有特定于平台的接口实现,例如平台A(对于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!");
        }
}

使用常量表达式:

private static final boolean PLATFORM_A = true;
 public static void print(string str)
  {
    if(PLATFORM_A )
    {
       printA(str);
    }
    else
    {
      printB(str);
    }
  }

这个代码怎么样?

    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;
        }
    }
}

您可以使用策略模式。

定义一次接口,并在操作系统特定的类中实现它。

    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
       }
    }

最新更新