Static Methods vs. Separate Class
Author |
Message |
Raknarg
|
Posted: Tue Feb 11, 2014 2:07 pm Post subject: Static Methods vs. Separate Class |
|
|
Hey guys, I'm curious what you think. Let's say I have a game with enemies. I have an enemy class to represent them Before I started Java, what I would do was create a separate class called EnemySystem to handle all the enemies, like storing them, updating them, enemy generation etc. However I recently learned how the static keyword in Java works, and I realized I could basically merge the two classes together by taking all the methods and variables in EnemySystem and turning them into static entries in my Enemy class. I thought it might make more sense too because I don't see me ever using more than one EnemySystem, so maybe it would be better to have them as static parts of my Enemy class.
What's your guys' opinions? |
|
|
|
|
|
Sponsor Sponsor
|
|
|
DemonWasp
|
Posted: Tue Feb 11, 2014 4:02 pm Post subject: RE:Static Methods vs. Separate Class |
|
|
Your question generally deals with "design patterns", which are basically just common ways of organizing code. See http://en.wikipedia.org/wiki/Software_design_pattern .
The one that applies best to this situation is the Singleton Pattern. What you should do is have many instances of Enemy (or Unit, etc), and a single instance of EnemySystem or UnitManager or whatever. Then you can get that instance using the static method EnemySystem.getInstance().
This lets you separate your concerns and code better, while maintaining some of the advantages of using static / global context (avoiding having to pass around object references, etc).
You should be aware that there are some very valid criticisms of the singleton pattern. One of the strongest objections is that it's inflexible. Suppose your game server wants to serve multiple games at once. With a single EnemySystem instance, this would be very messy; with one EnemySystem per logical game, it could be trivial. |
|
|
|
|
|
|
|