20.10.2021
Flyweight
The Flyweight Pattern is used to share common states between objects and therefore decrease the amount of objects created while optimizing the memory footprint and performance. The pattern is based on a Factory that stores and looks up created objects or shared states of objects.
Example:
public class Block {
BlockModel blockModel;
Location location;
...
}
public class BlockFactory {
private static Map<TextureType, BlockModel> gameObjectCache
= new HashMap<>();
public static BlockModel createBlockModel(TextureType texture) {
return gameObjectCache.computeIfAbsent(texture, BlockModel::new);
}
}
public class WorldEditor {
List<Block> blocks = new ArrayList<>();
public void buildBlock(TextureType texture, Location location) {
BlockModel blockModel = BlockFactory.createBlockModel(texture);
blocks.add(new Block(blockModel, location));
}
public void draw() {
blocks.forEach(Block::draw);
}
public static void main(String[] args) {
WorldEditor worldEditor = new WorldEditor();
for(int i = 0; i < 100; i++) {
worldEditor.buildBlock(TextureType.WATER, Location.getRandomLocation());
}
worldEditor.draw();
}
}
Standort Hannover
newcubator GmbH
Bödekerstraße 22
30161 Hannover
Standort Dortmund
newcubator GmbH
Westenhellweg 85-89
44137 Dortmund