The flyweight structural pattern allows you to represent more items in your application as class instances without using up all your computer memory.

It does this with four steps:

  1. Separate the data members in your classes that you’re considering for this pattern into intrinsic and extrinsic state. Intrinsic state is common for all instances and belongs with shared instances of the class. Extrinsic state is anything that’s unique to each instance and can’t be shared.
  2. Use either a factory or a modified singleton to create a pool of shared objects where there’s just one object of each type that’s participating in this pattern. There should only be one instance of each class with the same intrinsic state.
  3. Pass the extrinsic state to each class method that needs it. You’ll likely have several data members that need to be kept separate like this and they can all be bundled into a context that gets passed to each method.
  4. And try to calculate the extrinsic state as much as possible. This will lead to even more memory savings.

This pattern shows you how to save a lot of memory when dealing with many instances of your classes. It’s likely to allow you to represent items as class instances that you wouldn’t have been able to consider before.