Skip to content

Flyweight

Roberto Fronteddu edited this page Feb 16, 2023 · 4 revisions

The Flyweight is a Structural Design Pattern. It shares an object in multiple contexts dividing its state into Intrinsic (state shared in every context, the state doesn't change regardless of where the object is used) and Extrinsic (context-specific state). We create objects with only intrinsic states and share them in multiple contexts. The client or user of objects provides the extrinsic state to the object to carry out its functionality.

Usefull when

  • We need many objects of a particular class and maintaining these instances is a performance concern.

UML

flyweight uml

  • Flyweight is the interface used by the client that typically requires the extrinsicState as a parameter.
  • The ConcreteFlyweight can be shared and only contains the intrinsicState. It also defines operations that can be done by specifying the extrinsicState (data/objects that can't be shared).
  • UnsharedConcreteFlyweight: Objects that are not shared
  • FlyweightFactory: Creates the flyweight and manages the sharing

Implementation steps:

  • Identify what can be shared (intrinsic) and what cannot (extrinsic)
  • Create an interface that defines common methods that accept the extrinsic state
  • in the shared flyweight add the intrinsic state and implement the methods
  • in the unshared flyweight, ignore the extrinsic state as we have the state within the object
  • Implement the factory that caches the flyweights and also provides a method to get them
  • Store or compute the extrinsic state in the client and use it when needed for flyweight operations.

Design Considerations

  • A factory is used to get easy access to the shared flyweight. Also good to keep track of the flyweights' instances.
  • Intrinsic state should be immutable
  • Usability of this pattern depends upon the presence of a meaningful extrinsic state in an object that can be moved out without any issue.
  • Strategy and State patterns can use this pattern.

Comparison with ObjectPool

Flyweight:

  • The state of a flyweight object is divided into a part that is shared (Intrinsic) and a part that is provided by a Client (Extrinsic and variable).
  • Clients will not typically change the Intrinsic state of flyweight as it is shared.

Object Pool:

  • A pooled object fully encapsulates its state.
  • The client can and will change the state of pooled objects.

Pitfalls

  • Maintaining extrinsic code is paid at runtime. Client code has to either maintain it or compute it every time it needs to use a flyweight.
  • Typical apps may not have lots of use for this pattern.

Real-Life Examples

  • java.lang.Integer Short, Byte, etc valueOf static method serves as the factory method. They cache values and return them.
Clone this wiki locally