1

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, e.g. 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?

nmnd
  • 105
  • 12
  • 1
    “…taking this approach would need me to specify which implementation should be used before building the application…” Why? Why can’t you include both implementations in your code, and write separate code that decides which one to use at runtime based on the `os.name` system property? – VGR Oct 23 '18 at 14:09

2 Answers2

2

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?

Hulk
  • 6,399
  • 1
  • 30
  • 52
0

java stores the OS name in it's standard properties so the following call should give you the OS name:

System.getProperty("os.name")
Dinomaster
  • 256
  • 1
  • 6