game-programming-patterns icon indicating copy to clipboard operation
game-programming-patterns copied to clipboard

Flyweight Pattern: alternate strategy with Java enum objects

Open BBauman opened this issue 8 years ago • 0 comments

As an intermediate example in the Flyweight Pattern write-up, an enum is presented as a way to maintain an independent collection of terrain types, eventually rejected because all the processing details end up in switch statements in the World class - prompting the move to instances of a Terrain object that are configured in the World class.

It may be worth pointing out that Java (and potentially other languages) offer a heavier variation on enums that allow for public and private methods and properties. This allows for the same usage as the object example, but allows all configuration to be encapsulated within the Terrain enum itself. Additionally, the enum structure will take care of limiting instances of each Terrain type to only one, removing the need for an object pool.

The only downside I can see is that all Terrain enum types are front-loaded, so you can't save memory on unused instances. Additionally, if you want to dynamically generate types, you likely wouldn't find this particularly useful.

BBauman avatar Aug 25 '17 23:08 BBauman