Also known as Cache



Use sharing to support large numbers of fine-grained objects efficiently.

Structure of design pattern

Flyweight pattern structure


// This flyweight class contains part of the fields, which describe a tree.
// These fields values are not unique for each tree; you won't find tree
// coordinates there. But several trees can have the same texture. And since
// that texture is usually BIG, you're wasting a lot of memory by keeping it
// million times for similar trees. That's why we extract texture to a separate
// object, which can be referenced from all those similar trees.
class TreeType is
    field name
    field color
    field texture
    constructor Tree(name, color, texture) { ... }
    method draw(canvas, x, y) is
        Create a bitmap from type, color and texture.
        Draw bitmap on canvas at X and Y.

// Flyweight factory decides when to re-use existing flyweight and when to
// create a new one.
class TreeFactory is
    static field treeTypes: collection of tree types
    static method getTreeType(name, color, texture) is
        result = treeTypes.find(name, color, texture)
        if (result == null)
            tree = new TreeType(name, color, texture)
        return tree

// Context object keeps unique part of tree's state. Application can create
// billions of these since they are pretty thin–just two integer coordinates and
// one reference.
class Tree is
    field x,y
    field type: TreeType
    constructor Tree(x, y, type) { ... }
    method draw(canvas) is
        type.draw(canvas, this.x, this.y)

// Tree and Forest classes are Flyweight's clients. You might merge them
// together if you don't plan to develop a Tree class any further.
class Forest is
    field trees: collection of Trees

    method plantTree(x, y, name, color, texture) is
        type = TreeFactory.getTreeType(name, color, texture)
        tree = new Tree(x, y, type);

    method draw(canvas) is
        foreach tree in trees

Implementations in Different Programming Languages