You are designing part of a large online multiplayer game responsible for creating enemy objects. Build a factory that creates an enemy for a requested color. For this exercise, color is the enemy's only property, and the caller specifies the desired color when requesting an enemy.
Use the following language-neutral API shape:
Enemy createEnemy(String color)
Input:
factory.createEnemy("teal")
Output:
Enemy(color="teal")
The factory returns an enemy whose color matches the requested value.
Input:
factory.createEnemy("amber")
Output:
Enemy(color="amber")
The returned object is configured with the caller's selected color.
Input:
factory.createEnemy("violet")
factory.createEnemy("violet")
Output:
Enemy(color="violet")
Enemy(color="violet")
Both requests produce enemies with the same requested color; the memory-optimized behavior for repeated requests is the subject of the follow-up.
Follow-up: Suppose each enemy occupies substantial memory and the game must create an extremely large number of them. How would you change the design to reduce memory usage?
The initial exercise focuses on a color-driven factory. The follow-up asks you to reconsider object sharing when many enemies have the same color and to distinguish data that can be shared from data that must belong to an individual enemy.