Download the working example demo code in java from my GIT repository –https://github.com/premaseem/designPatterns/tree/4bb9beca7bab5b5e71d02b76e4f1ad48fce4aca6/ZipDownloadableProjects
Flyweight is used when there is a need to create high number of objects of almost similar nature.
For example assume we are working with an application that maps stars from universe. In this application if we are going to create an object for every star then think of it how much memory we will need. There could be max 10 types of stars (intrinsic) which would be placed at different coordinates (extrinsic). The idea it to create only 10 object and place them at different coordinates directed by client. This is really handy with video games and graphic application especially on Mobile devices where memory is critical.
High number of objects consumes high memory and flyweight design pattern gives a solution to reduce the load on memory by sharing objects. Each “flyweight” object is divided into two pieces: the state-dependent (extrinsic) part, and the state-independent (intrinsic) part. Intrinsic state is stored (shared) in the Flyweight object. Extrinsic state is stored or computed by client objects, and passed to the Flyweight when its operations are invoked.
Use sharing to support large numbers of fine-grained objects efficiently.
Designing objects down to the lowest levels of system “granularity” provides optimal flexibility, but can be unacceptably expensive in terms of performance and memory usage.
When to Use Flyweight Design Pattern
- Need to create large number of objects.
- Because of the large number when memory cost is a constraint.
- When most of the object attributes can be made external and shared.
- The application must not mandate unique objects, as after implementation same object will be used repeatedly.
- Its better when extrinsic state can be computed rather than stored. (explained below)
- Ensure that object overhead is an issue needing attention, and, the client of the class is able and willing to absorb responsibility realignment.
- Divide the target class’s state into: shareable (intrinsic) state, and non-shareable (extrinsic) state.
- Remove the non-shareable state from the class attributes, and add it the calling argument list of affected methods.
- Create a Factory that can cache and reuse existing class instances.
- The client must use the Factory instead of the new operator to request objects.
- The client (or a third party) must look-up or compute the non-shareable state, and supply that state to class methods.