Flyweight Pattern in JavaScript

September 1, 2021 · 3 min readLucian Ciobanu
Tags:JavaScript

Flyweight pattern is a structural design pattern which are all aimed at altering the composition of objects.

Flyweight is usefull when we have a big number of objects with a common part so rather than storing the same combination of properties many times, we use the fact that objects share refernce to the memory in JS so that we save the amount of overhead memory used.

In the code snippet below, I'm adding an implemetation example of this design pattern.

var Task = function(data) {
    this.name = data.name;
    //can be removed when using flyweight design
    this.priority = data.priority;
    this.project = data.project;
    this.user = data.user;
    this.completed = data.completed;
    //to here
}

//flyweight style
var Task = function(data) {
    this.name = data.name;
    this.flyweight = FlyweightFactory.get(data.project, data.priority, data.user, data.completed);
}

Task.prototype.priority = function() {
    this.flyweight.priority;
}

function Flyweight(project, priority, user, completed) {
    this.priority = data.priority;
    this.project = data.project;
    this.user = data.user;
    this.completed = data.completed;
}

var FlyweightFactory = function() {
    var flyweights = {};
    var get = function(project, priority, user, completed) {
        if(!flyweights[project + priority + user + completed]) {
            flyweights[project + priority + user + completed] = new Flyweight(project, priority, user, completed);
        }
        return flyweights[project + priority + user + completed];
    };
    var getCount = function() {
        var count = 0;
        for (var f in flyweights) count++;
        return count;
    }
    return {
        get: get,
        getCount: getCount
    }
}()
//to here

function TaskCollection() {
    var tasks = {};
    var count = 0;
    var add = function(data) {
        tasks[data.name] = new Task(data);
        count++;
    };
    var get = function(name) {
        return tasks[name];
    };
    var getCount = function() {
        return count;
    };
    return {
        add: add,
        get: get,
        getCount: getCount
    };
}

var tasks = new TaskCollection();

var projects = ['none', 'courses', 'training', 'project'];
var priorities = [1, 2, 3, 4, 5];
var users = ['Jon', 'Erica', 'Amanda', 'Nathan'];
var completed = [true, false];

var initialMemory = process.memoryUsage().heapUsed;

for(let i=0; i<10000; i++) {
    tasks.add({
        name: 'task' + i,
        priority: priorities[Math.floor((Math.random() * 5))],
        project: projects[Math.floor((Math.random() * 4))],
        user: users[Math.floor((Math.random() * 4))],
        completed: completed[Math.floor((Math.random() * 2))]
    });
}

var afterMemory = process.memoryUsage().heapUsed;

console.log('used memory ' + (afterMemory - initialMemory) / 1000000);

Hope this helped!

Cheers,
Lucian

Picture of author

Web Development & Software Delivery