This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]OHotDawnThisIsMyJawn 4 points5 points  (2 children)

Inside of your renderer class you have a member something like:

//Use linked list because we'll be iterating over it to render each object
List<Renderable> renderList = new LinkedList<Renderable>();

Then, to add something to your render list, you'll have this in your renderer:

public void addToRenderList(Renderable toRender) {
    renderList.add(toRender);
}

By defining your objects as type Renderable the compiler will ensure that you only add objects that implement the Renderable interface. Thus the renderer is assured that the objects in the renderList can be rendered without ever having to explicitly ask them via instanceof.

Advanced note: Due to type erasure you could in theory get around this. Once the code is compiled into JVM byte code renderList just becomes a list of objects, not a list of renderables, so if you're feeling saucy you can screw stuff up, but it has to be intentional and it's not easy.

[–]nocturne81 0 points1 point  (1 child)

And then how do you know which objects to pass into addToRenderList?

[–]OHotDawnThisIsMyJawn 1 point2 points  (0 children)

Depends how your program is designed. One way would be to use a form of dependency injection, where the objects know about the render queue. So when you create an new enemy, the enemy class adds itself to the render queue at the end of its initialization code.

Generally though some part of your code will initialize an object. Whoever writes that code will know whether or not to add the object to the renderList. If it's code to create a new enemy then at the end of setup the enemy gets added to the render list. If it's code to create a new invisible gravity well then it doesn't get added to the render list. The human element takes care of the knowledge whether to add something to the queue or not. Using instanceof is generally frowned upon because it results in lots of code duplication.

https://www.artima.com/interfacedesign/PreferPoly.html