11. Design Pattern: Flyweight
It is one of the structural design patterns that is used to reduce the number of objects created to improve the memory footprint of an application. It is usually employed whenever we have limited memory or we can reuse the already existing similar kind of objects. It also helps in improving performance.
Let’s take an example of an application where the Flyweight pattern can be applied to improve its memory footprint. Notepad++, A Text Editor which we want to implement. For simplicity, Assume we can write anything in the notepad++ using A-Z, a-z, and 0–9, space characters.
A Client writes a paragraph using the mentioned characters. The same character would be repeating a couple of times. Can we create an object for those characters just once in the first use and reuse the same object in future uses?
From the above image, it is clear for every letter to print, it requires 3 things:
- x coordinate
- y coordinate
- character itself. (it is a common property that can be reused across multiple letters)
public class Letter {
private int xCoordinate;
private int yCoordinate;
private char character;
}If we go with this object, we need to create as many objects of the Letter class as we want to write in Notepad++. What It means is if there are 1000 letters in a paragraph, 1K objects of this class would be created which is an expensive operation. How do we solve this issue with the Flyweight pattern?
How to implement Flyweight Pattern?
Few things to keep in mind while implementing the Flyweight pattern:
- Remove the properties from the class which vary for different instances to make the class flyweight. For example. x and y coordinates must not be part of the Letter class as they vary for every letter instance.
- These extrinsic properties must be passed to the flyweight class’s method at runtime.
- The Flyweight class is an immutable class. Once its object is created, must not be edited.
- We need to cache the flyweight class objects once created to be reused as and when needed.
To understand it better, we will implement the Text Editor using the Flyweight pattern.
Get Shivanshu Goyal’s stories in your inbox
Join Medium for free to get updates from this writer.
1. Create an Interface
public interface Letter {
public void display(int row, int column);
}2. Have a concrete implementation for the interface.
public class EditorCharacter implements Letter {
private char character;
private String fontType;
public EditorCharacter(char character, String fontType){
this.character = character;
this.fontType = fontType;
}
public char getCharacter() {
return this.character;
}
public String getFontType() {
return this.fontType;
}
//no need to create setters as this object needs to be immutable
@Override
public void display(int row, int column) {
//display the character of particular font and size
//at given location
}
}3. There will be a factory that takes care of creating and caching these EditorCharacter objects.
public class LetterFactor {
//cache to store the letter for which object is already created or requested
private static Map<String, Letter> characterCache = new HashMap<>();
public static Letter crateLetter(char characterValue, String fontType){
String key = fontType + "_" + characterValue;
//returns from the cache if available
if(characterCache.containsKey(key)) {
return characterCache.get(key);
} else {
EditorCharacter characterObject = new EditorCharacter(characterValue, fontType);
characterCache.put(key, characterObject);
return characterObject;
}
}
}4. Client
public class Client {
public static void main(String[] args) {
/*
* Let' say my text is "Hello, this is Flyweight article!!"
*
*/
//to add letter l at 3 position
addLetter('l', "Arial", 0, 2);
//to add letter l at 4position
addLetter('l', "Arial", 0, 3);
//only one object for character 'l' of Arial type will be created
//regardless of how many times it is being used.
}
}
private static void addLetter(char characterValue, String fontType, int x, int y) {
Letter letter = LetterFactory.createLetter("l", "Arial");
letter.display(x, y);
}Famous Applications
- Text Editor
- E-Game where we create the same type of player at different locations.
Thanks for reading!!









