简体   繁体   English

如何根据操作系统动态继承?

[英]How to dynamically inherit depending on operating system?

I am developing for two operating systems. 我正在开发两个操作系统。 Each has a specific implementation of BaseClass . 每个都有一个特定的BaseClass实现。 I would like to abstract these implementations. 我想抽象这些实现。 My idea is to use an interface both of the implementations implement and then return the OS specific class using the factory pattern. 我的想法是使用两个实现的接口,然后使用工厂模式返回特定于OS的类。 This would look similar to this . 这看起来与类似。

However taking this approach would need me to specify which implementation should be used before building the application, eg by a constant variable holding the name of the OS ( platform variable in the linked answer). 但是,采用这种方法将需要我在构建应用程序之前指定应使用哪种实现,例如,通过保存OS名称的常量(链接答案中的platform变量)。 This seems to be a bad design choice to me. 对我来说,这似乎是一个糟糕的设计选择。 Is there another way to define which OS to build for? 还有另一种方法来定义要构建的操作系统吗?

You don't. 你不知道

This is not the way Java works. 这不是Java的工作方式。 Java programs are not compiled for a specific target system, they are supposed to be portable and work on all systems. Java程序不是为特定的目标系统编译的,它们应该是可移植的并且可以在所有系统上工作。 See Possible to run JAR file on any OS? 请参阅可以在任何操作系统上运行JAR文件?

If you need to do something that is really OS specifc, you can however use system properties to find out which OS the program is running on at runtime. 但是,如果您需要执行某些特定于操作系统的操作,则可以使用系统属性来找出程序在运行时在哪个OS上运行。 You can then use this information to choose an appropriate implementation in some kind of factory, but this is a runtime decision. 然后,您可以使用此信息在某种工厂中选择适当的实现,但这是运行时的决定。

Some ways to find out the OS: How do I programmatically determine operating system in Java? 查找操作系统的一些方法: 如何以编程方式确定Java的操作系统?

java将操作系统名称存储在其标准属性中,因此以下调用应为您提供操作系统名称:

System.getProperty("os.name")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM