DEV Community

Coder
Coder

Posted on • Originally published at itscoderslife.wordpress.com on

Flyweight Design Pattern [Structural]

Intent: The flyweight pattern is used to reduce the memory usage and the creation costs for similar objects that rely on the same data.

  • Instead of creating multiple objects, the flyweight pattern shares one instance to represent multiple objects.
  • Each flyweight object is divided into two pieces, the state-dependent extrinsic part, and the state-independent intrinsic part.
  • The intrinsic state is stored in the flyweight object.
  • To implement the flyweight pattern we must identify the immutable state free intrinsic set of properties from the state-dependent extrinsic state.
  • The extrinsic part should be managed by clients and passed to the flyweight instance, whereas the immutable state of the flyweight should be protected from changes.

The flyweight pattern allows the sharing of common objects that can be used identically saving memory by reducing the number of object instances at runtime.

Example from sourcemaking.com:

The Flyweight uses sharing to support large numbers of objects efficiently. Modern web browsers use this technique to prevent loading same images twice. When browser loads a web page, it traverse through all images on that page. Browser loads all new images from Internet and places them the internal cache. For already loaded images, a flyweight object is created, which has some unique data like position within the page, but everything else is referenced to the cached one.

  • The flyweight pattern should be used to support a large number of similar objects via sharing.
  • Instead of creating multiple objects, the flyweight pattern shares one instance to represent multiple objects.
  • To implement the flyweight pattern we must separate the immutable set of properties from the state-dependent part.
  • The intrinsic part should be stored in the flyweight object whereas the state-dependent extrinsic part should be managed by clients. The extrinsic state is stored or computed by client objects and passed to the flyweight when its operations are revoked.

Disadvantages:

Common thing is clients can change the immutable state of the flyweight. The intrinsic state of the flyweight objects must not be modified by callers.

Another wrong implementation is not protecting the flyweight from concurrent access. A shared flyweight instance may be accessed in parallel from several different strats. Therefore, threat safety is imperative.

Latest comments (0)