I have a very simple Player class in java that uses some strategies object all inheriting from the interface PlayerStrategy.
Some implementations of PlayerStrategy are simple but a few others are so resource intensive that I need to make sure I free resources properly when the strategy stops being used. Those strategies have an additional method: turnOff() that takes care of that.
Now if Player leaves the game I’d like it to call turnOff() in all the strategies it has that need it.
The problem is that only a few strategies need turnOff() so I don’t feel comfortable adding that method to the PlayerStrategy interface.
Right now when a Player stops playing it checks through reflection if the method turnOff() exists in its strategy. But it’s clunky and ugly. Is there a better way?
Avoid Reflection: Reflection is a bad idea. Wherever you can (and it seems you can), avoid it.
It’s Good to have
turnOff()in the Interface: If you have to use interface… believe me addingturnOff()orcleanup()method is a good idea; even if most of the subclasses will have just empty curly brackets. You wouldn’t need to do extra work if they get updated in future to use some resource that requires a clean up.You can get What You Want but the Cost is Higher: If you are really rigid and sure that subclasses wouldn’t extend any other class. You may make the
PlayerStrategya abstract class withturnOff()as empty method. This will solve both your issue, but will limit the subclasses ability to extend other class.