开发者

How would you call a method from all instances of a class?

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 abstra开发者_运维知识库ct 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.


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜