- the object's constructor needs parameters unknown during initalization
- there will be many instances of such object (possibly unknown number of them)
audioPlayer = new AudioPlayersPool(10, -> new AudioPlayer) # the pool will create 10 instances of the player clock = new Clock createCountdown = (seconds) -> new Countdown(clock, seconds) # we don't know how many countdowns we'll need createTask = (attributes) -> new Task(serverSide, gameWorld, clock, earth, cannon, attributes) createGameSession = (attributes) -> new GameSession(serverSide, createTask, attributes) game = new Game(serverSide, createGameSession)
The last example shows another advantage. Before refactoring and moving GameSession and Task creation outside of Game class, the initialization looked like this:
game = new Game(serverSide, gameWorld, clock, earth, cannon)
The first, refactored version is much better, because game only needs to create gameSessions, not to deal with clock or gameWorld directly. Introducing factories leads to passing more specialized dependencies to other objects. Often it means less dependencies as well. As a result, objects have less knowledge about other parts of the application - which seems to be a good thing.
I hope you'll find factories useful in your code too!