flyweight - Harsh4999/Design-Patterns GitHub Wiki

Flyweight

Use

  • It allows us to share an object in multiple contexts. Instead of sharing entire object, which may not be feasible, we divide object in 2 parts: Intrinsic & Extrinsic state
  • We create objects which only intrinsic state and share them in multiple contexts
  • We use a factory class to initiate an object

Uml

  • Flyweight= Interface for client which define methods and operation which accept extrinsic state to be passed to it
  • Concrete Flyweight = Implementation of flyweight, its implemented with only intrinsic state in it
  • Unshared Concrete Flyweight = Objects of these are not shared, its objects will have all the states
  • Flyweight Factory = Used by the client provides instances of flyweights, it takes care of sharing
  • Client = It computes and stores the extrinsic state of used flyweights.

Implementation

  • Identify intrinsic and extrinsic state of our object
  • We create an interface of shared flyweight to provide common methods that accept extrinsic state
  • In unshared flyweight we ignore the extrinsic state as we have all state within object
  • Flyweight factory will cache flyweights and also provide methods to get them client will be using this to get flyweight
  • In client we either maintain extrinsic state or compute it on runtime when using flyweight.
  • We can divide the Flyweight into 2 parts one which will be consistent and be same all over (Intrinsic) and other part will be changing as per situation and will be provided by client (Extrinsic).
  • In concrete flyweight we will accept extrinsic flyweight from client and will have intrinsic flyweight inside and then combine both of them in order to use object
  • Its really useful when we have large information loaded
  • A factory is always needed to access flyweight instance
  • Eg: Integer wrapper class