Flyweight Design Pattern
Flyweight design pattern is used to support sharing of objects when the objects are in large number with details to granularity of
The intent is to share the fine-grained objects to make the system efficient.
- Use sharing to support large numbers of fine-grained objects efficiently.
It looks good to have objects to the granularity of system as it gives flexibility in design but having large number of
objects may make the system complex and affect the efficiency.
- Having large number of objects to the granularity of system makes the system complex and inefficient.
We can have the shared object called flyweight which can be used in multiple context. So we will identify what information is
independent for object which is related to the object context. The object will have independent information so that it can be
shared. The context information will depend on object context as it varies and will be provided by client. The independent
information is called intrinsic state and context information is called extrinsic state. The operation of flyweight object
will be done based on these states.
- Come up with an approach to share the objects at fine granularity to make the system simple and efficient.
Where it is applicable?
- There are large number of objects to the granularity of system.
- There can be differentiation of intrinsic and extrinsic state.
- The objects can be shared with their independent information.
How they work together?
- FlyweightFactory class manages the pool of Flyweight objects. If flyweight object already exists then it
provides the instance from the pool, otherwise it creates new and add it to the pool.
- Flyweight class provides the interface Operation with extrinsic state.
- ConcreteFlyweight class implements the method Operation and has intrinsic state which is independent of its
- UnsharedConcreteFlyweight is not shared and can have Flyweight object in their structure.
- Client gets the Flyweight object through FlyweightFactory. FlyweightFactory manages the pool of flyweight objects, if
its already existing then it provides the same, otherwise it creates new one, adds it to the pool and provides it to the
- Client gets or computes the extrinsic state information. It provides the extrinsic state information while using
interface Operation. ConcreteFlyweight does the operation based on intrinsic and extrinsic state.
- So we can see the number of objects will be drastically reduced by sharing the flyweight objects. This will have
reduction of storage, decrease in memory requirement and will obviously make the system efficient.
Suresh Kumar Srivastava is founder of online learning site coursegalaxy.com and author of popular books "C In Depth",
"Data Structures Through C In Depth". He has 18+ years experience in industry and worked on architecture and design of
multiple products. This article is from his courses on design patterns.
Design Patterns in C#