Flyweight pattern
Definition
Use sharing to support large numbers of fine-grained objects efficiently.
Flyweight, the word, refers to something that weighs almost nothing.
Introduction
As a Java programmer you’ve probably heard to “Think in terms of objects”. Designing objects to the lowest levels of system “granularity” promote flexibility in the application. But, as a good programmer you also need to think about the performance of the application, in terms of the amount of resources required to run it. When you are dealing with a large number of objects, you need to be concerned about the resources the objects will consume. Each will need memory, and creating each will need CPU cycles.
Imagine you need 1000 car objects in an online car racing game, and the car objects vary only in their current position on the race track. Instead of creating 1000 car objects and adding more as users join in, you can create a single car object with common data and a client object to maintain the state (position of a car). The Flyweight Pattern reduces repeated data, thus reduces memory consumption when dealing with large numbers of objects.
The Flyweight pattern is a part of the classic Gang of Four structural pattern family. We have already learned about some of the other patterns of this family: Adapter, Bridge, Composite, and Decorator. The Flyweight pattern, similar to those patterns is concerned with relationship between classes and objects, but through a whole new concept of object sharing. What this pattern says is that if an application requires a large number of fine-grained objects, share them instead of repeated instantiation. The object you share is referred as a flyweight.
To become familiar with the Flyweight pattern, a concept to understand is how the internal state of a flyweight is represented. You can categorize the internal state into:
- Intrinsic data: Information that is stored in the flyweight object. The information is independent of the flyweight’s context, thereby making it sharable. While applying the pattern, you take all of the objects that have the same intrinsic data and replace them with a single flyweight.
- Extrinsic data: Information that depends on the flyweight’s context and hence cannot be shared. Client objects stores and computes extrinsic data and passes it to the flyweight when it needs it.
Implementation
Continuing with the car racing example, consider we need two types of cars: Midget and Sprint race cars. We can create an abstract base class RaceCar with three fields:
name of type String for the name of the car speed of type int for the maximum car speed horsepower of type int for the engine power Objects of a concrete subclass, such as FlyweightMidgetCar will store the same set of values for the preceding fields.
. . . name=“Midget Car”; speed=140; horsepower=400; . . . This means, these values can be shared between various FlyweightMidgetCar objects, and so we consider them as intrinsic data. This is common data that will not change and can be shared with other objects.
Consider in the base class, we have a moveCar(int currentX, int currentY, int newX ,int newY) method that we override in the FlyweightMidgetCar subclass. This method defines the position of each FlyweightMidgetCar object at a given time, and hence cannot be shared. So we consider the car position passed to moveCar() as extrinsic data.
Now that we have categorized the internal states of FlyweightMidgetCar into intrinsic and extrinsic data, we can make it a flyweight object. Similarly, we can make FlyweightSprintCar or any other object that extend RaceCar as flyweight objects.
To manage our flyweight objects, we need a factory – a class that uses a pool (implemented as some data structure) to store flyweight objects. When client request a flyweight object for the first time, the factory instantiates a flyweight, initializes it with its intrinsic data, and puts it in the pool, before returning the flyweight to the client. For subsequent requests, the factory retrieves the flyweight from the pool and returns it to the client. We will name the class CarFactory.
We will also need a client class, RaceCarClient that will retrieve a flyweight (already initialized with its intrinsic data) from the factory and pass the extrinsic data to the flyweight. In the context of our example, the client will manage and pass the position (extrinsic data) of a car by calling the moveCar(int currentX, int currentY, int newX ,int newY) method of the flyweight.
Participants
- Flyweight (RaceCar): Abstract class or interface for flyweight objects. Declares method through which flyweights can receive and act on extrinsic state. Although Flyweight enables sharing, it is not mandatory that all Flyweight subclasses must be shared.
- ConcreteFlyweight(FlyweightMidgetCar and FlyweightSprintCar): Extends/Implements Flyweight to represent flyweight objects that can be shared.
- FlyweightFactory(CarFactory): Creates and manages flyweight objects. When a client requests a flyweight object, FlyweightFactory provides an existing one or creates a new one, if it does not exists.
- Client(RaceCarClient): Requests FlyweightFactory for a flyweight object, and then computes and passes the extrinsic data to it.
Conclusion
When you’re dealing with large scale systems, the Flyweight Pattern is something to consider. It can help save system resources. There’s a lot of buzz about ‘Big Data’ in the industry. What happens when you’re processing big data?? You may see a use case for the Flyweight Pattern.
When you are developing Enterprise Applications with the Spring Framework, if you are in situations where you have a large amount of objects sharing some common state and consuming large amount of memory, the Flyweight pattern may be exactly what you are looking for.