20.10.2021 |


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.



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() {

    public static void main(String[] args) {
        WorldEditor worldEditor = new WorldEditor();
        for(int i = 0; i < 100; i++) {
            worldEditor.buildBlock(TextureType.WATER, Location.getRandomLocation());
Zur Übersicht

Mehr vom DevSquad...

Sophia Brandt

Solid.js - Eine deklarative, effiziente und flexible JavaScript-Library zum Bauen von Benutzeroberflächen

Sven Röttering