简体   繁体   中英

How to dynamically inherit depending on operating system?

I am developing for two operating systems. Each has a specific implementation of 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. 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). 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 programs are not compiled for a specific target system, they are supposed to be portable and work on all systems. See Possible to run JAR file on any OS?

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. 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将操作系统名称存储在其标准属性中,因此以下调用应为您提供操作系统名称:

System.getProperty("os.name")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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