I've been reading about dependency injection and have a simple question. I can understand how via constructor or setter injection required dependencies are autowired by the DI framework. What happens when an object decides it needs to create a new object due to some business process? Do I need to always create a Factory in these situations? To make it a less abstract question, here is an example.
Let's say I'm writing a game of Asteriods. There's a ship in the middle which can spin around and shoot the asteriods. Assume that the ship has been created and approriate things injected. When playerShip.shoot()
is called we need to create a bullet
object. The bullet object needs to know which way it is going (direction
) and where to start (point
).
Normally, I would do something like this:
bullet = new Bullet( direction, point );
However, that tightly couples the PlayerShip class to the Bullet class. How should this work under dependency injection? Do I need to create a BulletFactory interface and inject an implementation of that into the ship?
Edit: I'm not actually writing asteriods. This was a simple example that I thought people would understand. I wanted something that needed to be created a runtime (not while "wiring up objects") that also had parameters to it's constructor.