views:

135

answers:

4

I am writing a basic game engine and have an abstract class that represents any object that can be drawn in the 3D world, however inside this class is an abstract method Render() which I would like called automatically by the engine on each draw phase. How could I implement this so that every class extending from my abstract class will automatically have Render() called?

I am using java, android sdk 2.2, and opengl es

+3  A: 

You can register every object which can be rendered to a class which will call render() on all your objects.

For example :

public class Registry{
    private static Collection<RenderedObject> register = new ArrayList<RenderedObject>();

    public static void add(RenderedObject obj){
        register.add(obj);
    }

    public static void renderAll(){
        for(RenderedObject obj : register){
            obj.render();
        }
    }
}

And you can register your objects into the registry within the constructor of your RenderedObject.

Colin Hebert
static variables is a *very bad idea* to use on Android.
aioobe
Reminds me a little bit of the observer pattern.
Helper Method
@aioobe, you can do the same thing without static environment. @Helper Method, it works the same way.
Colin Hebert
@Helper: Something obvious and simple like this is a named "pattern" now? What's next? The variable pattern? The addition pattern?
Matti Virkkunen
@Colin, of course. I'd even go as far as saying "you *should* do it without static environment."
aioobe
@aioobe and static variables are bad on Android because...?
Lo'oris
@Matti Virkkunen this is basically an observer pattern: objects register on creation and get called on update (sometime later). It only lacks a proper interface.
atamanroman
A: 

You have to retain references to all the objects you want to draw. Then, when you want to draw them, use a for-each loop to call the method on all objects you have.

Vivien Barousse
A: 

Maintain a list of all the objects, loop through it and call the method.

Matti Virkkunen
+1  A: 

You can make a Proxy of your Engine:

public class RenderingEngine implements Engine {
    private Engine originalEngine;
    private Collection<AbstractRender3DObject> items;

    public RenderingEngine(Engine originalEngine) {
      // assing
    }
    public void draw() {
         originalEngine.draw();
         invokeRender();
    }

    private void invokeRender() {
       for (AbstractRenderItem item : items) {
           item.render();
       }
    }

    public void register(Object3D item) {
         if (item instanceof AbstractRender3DObject) {
             items.add(item);
         }
         super.register(item);
    }
}

I don't know the framework you are using, so I assumed some method and interface names. But the idea is as above.

Bozho
Note that identifiers starting with a digit is illegal in Java.
BalusC
hah, of course. thanks :)
Bozho