Is there a way of determining whether the "main" is Android or Java
I recently wrote a Java playing card game and have all the game logic written within one Class called Game. Where possible I tried to keep all GUI handling outside of this class. I am now trying to convert this game to an Android application.
Within the playAutomaticTurn() method (used by both the Android Activity and the Java desktop application) I then call another method within Game if the computer player wishes to announce that they've won. This plays two sound effects dependent on the result using a SoundEffect class that I created (uses the javax.sound.sampled.* libraries).
Rather than completely rewrite the code to move the sound effects back to the calling method (I guess I'd have to return a status from my announceWin() method and in turn return this from playAutomaticTurn()) is there a succinct way to determine whether the main calling application is an Android one?
In this way I could put an if or case statement in place and handle the sound effects differently?
E.g.
if (androidApp) {
playAndroidSoundEffect
} else {
playJavaxSoundEffect();
}
Or is the only way to create a constant declaration at the start of the Class and compile it with different values for the Java and Androi开发者_开发问答d versions?
E.g. to compile a version for Android (without yet implementing the Android sounds)
private static final boolean SOUND = false;
//...
if (SOUND)
playJavaxSoundEffect();
Thanks for any assistance and advice you can offer.
Sparkling lots of if
s around your code is bad practice, I recommend creating interface(s) which capture the platform specific behavior, like
interface SoundService {
playSound(/* ... */);
}
This way you can create multiple implementations of your interfaces, including a trivial NoOp
implementation for the lazy, and have all the platform specific code in very view places.
Shot in the dark
Could you use reflection to make a boolean for a library that is only available in android:
boolean isAndroid = false;
try {
Context.class.getMethod("getApplicationContext", null);
isAndroid = true;
} catch (NoSuchMethodException e) {
isAndroid = false;
} catch (Exception e) {
isAndroid = false;
}
Using Waldheinz and Blundell ideas we can create basic factory pattern , we can see to that Game need not know about platform dependency ...And all Sound object initialization is done in factory and decision of what kinda of object to create would be decision of factory...and Blundell's approach can be used for the same Please find example factory pattern code http://www.devdaily.com/java/java-factory-pattern-example
精彩评论