Libgdx: Objects creating other objects

163 views Asked by At

I have kind of a general question about a simple game architecture. In my game I have these classes:

  1. Main class who's responsible for drawing and rendering.
  2. Ball object which has a few attributes and update() function that does certain things.

The main class has an array of all exist ball instances and the render() function is responsible to run through all of them and call their update(). Also, the main class has createBall() function that creates another instance.

Let's say one of the instances wants to create another ball in the game (through his update()). Which way is the correct way to do so:

  1. Every ball gets in his constructor the Main Class instance (The main class passes it self to the ball when creating it) and calls main.createBall();
  2. Every ball has an array of "requests" that the main class reads and understands what the ball wants to create.

It's supposed to be a generic question because it kinda defines the way instances communicate with the main class.

Thank you!

1

There are 1 answers

4
Phil Anderson On BEST ANSWER

From an OOD perspective, I'd have a third class that knew about creating balls. I'd instantiate it in Main, and pass it into the Ball class in the constructor. You could call this class BallFactory.

The Ball class would call addRequest() when it wanted to create a Ball, and the Main class would call processRequests() when it was ready to do the actual creation. The list itself would remain a private implementation detail of the factory, which is good encapsulation.

This gives us better separation of concerns.

The options you suggest will both work, but from a pure OO point of view they're not ideal because they reduce the cohesion of either the Main (option 1) or Ball (option 2) class.