Reputation: 117
I have created a rather complicated piece of (Java) code for a game I am working on. I'm fairly sure I will need to change it in the future to optimize or otherwise change the exact functioning. The code can efficiently loop through a subset of the game entities.
The problem is that while looping over this subset different codes should be executed. For example:
There are several simple solutions possible:
As one can see, both efficient and easily manageable code is required. Are there any other solutions possible with the Java programming language? I would prefer to supply the code with a pointer of some sort to the method that takes care of the specific needs but I do not know how or if that is possible in Java.
Besides the hope for a neat solution, I ask this because I want to learn every in and out of Java! Thanks for any answers!
Cheers, Armored
Upvotes: 2
Views: 150
Reputation: 4826
Declare an interface with methods that the looping code calls, then supply the looping code with different implementations of the interface depending on what you need it do to.
This is commonly referred to as the Template Method Pattern
Upvotes: 3
Reputation: 19882
You may first want to sperate you game entities into different classes so that each class/entity contains its own code and knows how to process it self. See http://en.wikipedia.org/wiki/Factory_method_pattern
Instead of using if/switch statements to determine what entitiy it is you could look at using Reflection. Or take it a step further and using some IoC container such as http://www.springframework.net/ this will be a step learning curve and probably overkill for now. but definatlly worth reading and learning more about.
Upvotes: 0
Reputation: 236
I am not sure if this is a solution to your problem, but what if you had an abstract class do the basic work of looping through the entities, and then have classes extend the abstract class, and these child class would then do the more specific things. Then, runtime, you could supply to the variable of the abstract class type actual classes, based on the (user's?) specific needs.
Upvotes: 0