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:

Flyweight

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();
    }
}
Zur Übersicht
Michael Virks

Mehr vom Devsquad...

Sophia Brandt

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

Sven Röttering

Proxy

Hallo, ich bin Jörg Herbst!

Ich bin der CEO von newcubator und freue mich über jede Nachricht!

* Pflichtfeld