Design Patterns:Flyweight
First thing here is to familiarize with the term “Flyweight”.
The term flyweight refers to the weight category of around 50 kilograms in boxing.That sounds like a low weight to me given that I vary between 70 kilograms and 80 kilograms and I am not all that hefty either.So,flyweight essentially hints at objects that are not that heavy.
What?What is the flyweight design pattern?
Flyweight design pattern is the design pattern that shares light weight instances of a class across multiple requests instead of instantiating new objects every time.String interning is an often cited example of the flyweight design pattern where Java maintains a pool of Strings and does not instantiate new ones every time a string is requested by the developer code.Instead,it just refers to the one that is there in the pool.
Why?Why is there a reason to adopt such a flyweight design pattern?
In an ecosystem where small objects are frequently created and destroyed,I can see that the flyweight design pattern would help lower the cost of the creation as well as the destruction by keeping the instances live for a longer time.Essentially,it is a means to share large number of light weight objects efficiently.
How?Who are the main actors in the FlyWeight pattern?
FlyWeightFactory:This is the factory that returns flyweights as requested.
This class usually saves a collection of the shared flyweights.When a particular flyweight is requested,the flyweight factory gets the flyweight from it’s collection/map and returns it back to the client.
FlyWeightInterface:This is the interface that the FlyWeight object implements.
FlyWeightImplementation:This is the class that implements the FlyWeight interface.
UnSharedFlyWeightImplementation: This is the class that represents FlyWeight instances that are not shared using the factory.FlyWeight pattern does not mandate that all instances be shareable.Only the instances that need to be shared needs to participate with the FlyWeightFactory.
interface FlyWeight{
void operation(int extrinsicState);
};
public class FlyWeightImplementation(){
void operation(int extrinsicState){
SOP(“FlyWeightImplementation “ + extrinsicState);
}
public class UnSharedFlyWeightImplementation(){
void operation(int extrinsicState){
SOP(“UnsharedFlyWeightImplementation “ + extrinsicState);
}
public class FlyWeightFactory{
HashMap<Integer,FlyWeight> map = new HashMap<Integer,FlyWeight>();
map.push(2, new FlyWeightImplementation());
map.push(3,new FlyWeightImplementation());
public FlyWeight getFlyWeight(int extrinsicState);
}