Html/Javascript widget

Sunday 11 September 2022

Flyweight

The flyweight software design pattern is a structural pattern adapter, bridge, composite, decorator, facade, flyweight and proxy that refers to an object that minimises memory usage by sharing some of its data with other similar objects.

Overview

The flyweight pattern is useful when dealing with large numbers of objects with simple repeated elements that would use a large amount of memory if individually stored. It is common to hold shared data in external data structures and pass it to the objects temporarily when they are used.
A classic example are the data structures used representing characters in a word processor. Naively, each character in a document might have a glyph object containing its font outline, font metrics, and other formatting data. However, this would use hundreds or thousands of bytes of memory for each character. Instead, each character can have a reference to a glyph object shared by every instance of the same character in the document. This way, only the position of each character needs to be stored internally.
    As a result, flyweight objects can:
  1. store intrinsic state that is invariant, context-independent and shareable (for example, the code of character 'A' in a given character set)
  2. provide an interface for passing in extrinsic state that is variant, context-dependent and can't be shared (for example, the position of character 'A' in a text document)

Clients can reuse Flyweight objects and pass in extrinsic state as necessary, reducing the number of physically created objects.

No comments:

Post a Comment