Contact Me

Flyweight

 The flyweight pattern is a design pattern that allows you to share objects to reduce the number of objects that need to be created, and to reduce memory usage and increase performance. This can be useful when you have a large number of objects that share a common state, and when the cost of creating and maintaining these objects is high.


Here is an example of the flyweight pattern in JavaScript:


class Flyweight {

constructor(sharedState) {

  this.sharedState = sharedState;

}

operation(uniqueState) {}

}

class ConcreteFlyweight extends Flyweight {

operation(uniqueState) {

  console.log(`ConcreteFlyweight operation with shared state ${this.sharedState} and unique state ${uniqueState}.`);

}

}

class FlyweightFactory {

constructor() {

  this.flyweights = {};

}

getFlyweight(sharedState) {

if(!this.flyweights[sharedState]) {

  this.flyweights[sharedState] = new ConcreteFlyweight(sharedState);

  }

return this.flyweights[sharedState];

}

}

const flyweightFactory = new FlyweightFactory();

const flyweight1 = flyweightFactory.getFlyweight('state1');

const flyweight2 = flyweightFactory.getFlyweight('state1');

const flyweight3 = flyweightFactory.getFlyweight('state2');

console.log(flyweight1 === flyweight2);

// Output: true

console.log(flyweight1 === flyweight3);

// Output: false

flyweight1.operation('unique state 1');

// Output: ConcreteFlyweight operation with shared state state1 and unique state unique state 1.

flyweight3.operation('unique state 2');

// Output: ConcreteFlyweight operation with shared state state2 and unique state unique state 2.


In this example, the Flyweight class is an abstract class that defines the interface for a flyweight object, and the ConcreteFlyweight class is a concrete implementation of the Flyweight class that represents a specific flyweight object. The FlyweightFactory class is a class that creates and manages flyweight objects, and has a getFlyweight() method for returning an existing flyweight object with a given shared state, or creating a new flyweight object if one does not exist.

To use the flyweight pattern, we create an instance of the FlyweightFactory class, and then call the getFlyweight() method on it, passing in the shared state of the flyweight object that we want to get or create.

The getFlyweight() method will return an existing flyweight object with the given shared state, if one exists, or create a new flyweight object with the given shared state if one does not exist.

This allows us to share flyweight objects and reduce the number of objects that need to be created and maintained, thereby reducing memory usage and increasing performance.