Flyweight Pattern
It is one of the structural design patterns.
It’s main intent as per GOF is “Use sharing to support large numbers of fine-grained objects efficiently”
This pattern should be used when we have high number of objects of almost same nature.
When we have high number of objects, memory consumption will be high
In this case, flyweight pattern helps in reducing the memory consumption by enabling the sharing of objects.
Sharing objects is the main key in this pattern.
In order to understand this pattern and its application properly, we need to have clear understanding of intrinsic and extrinsic properties of an object.
What are intrinsic and extrinsic properties ?
Intrinsic properties make the object unique and extrinsic properties are passed by the client code which will be used by the object to perform different operations
Extrinsic properties are also known as non-shareable properties of a class which are supplied from client.
Let’s see how Flyweight pattern works
This pattern mainly reduces the memory consumption when we have huge number of objects.
In order to do that, it creates cache of objects in a Hashmap and re-use those objects only instead of creating new objects all the time.
Example :
Assume we have a class called “Alphabet”.
How many objects will be required to represent each Alphabet ?
26 for lower case and 26 for upper case and total 52 objects are required.
Now assume we have to represent each alphabet with some font, color and size
Now we will end up with huge number of objects
Example :
Object 1 : Alphabet A with font italic , color blue and size 12
Object 2 : Alphabet A with font italic , color blue and size 14
Object 1 : Alphabet A with font italic , color blue and size 16
Object 1 : Alphabet A with font italic , color red and size 12
. . .
. . .
and so on.
Just for alphabet “A” will have so many objects, think of 52 alphabets.
In order to reduce the number of objects, we need to use flyweight pattern
We need to implement below 3 points to achieve flyweight pattern
1 ) First we need to identify intrinsic and extrinsic properties of a class
2 ) Create a cache of objects using Hashmap
3 ) Reuse the objects from cache
Implementation of flyweight pattern
Let’s consider the example of Forest where we will have many trees
Assume we need to grow similar trees in different parts of a forest.
Step 1
Create a class called Tree
- package com.kb.flyweight;
- import java.awt.Graphics;
- public class Tree {
- private int x;
- private int y;
- private TreeType type;
- public Tree(int x, int y, TreeType type) {
- super();
- this.x = x;
- this.y = y;
- this.type = type;
- }
- public void draw(Graphics g) {
- type.draw(g, x, y);
- }
- }
package com.kb.flyweight; import java.awt.Graphics; public class Tree { private int x; private int y; private TreeType type; public Tree(int x, int y, TreeType type) { super(); this.x = x; this.y = y; this.type = type; } public void draw(Graphics g) { type.draw(g, x, y); } }
Step 2
Create a class called TreeType
- package com.kb.flyweight;
- import java.awt.Color;
- import java.awt.Graphics;
- public class TreeType {
- private String name;
- private Color color;
- public TreeType(String name, Color color) {
- this.name = name;
- this.color = color;
- }
- public void draw(Graphics g, int x, int y) {
- g.setColor(color);
- g.fillOval(x - 5, y - 10, 10, 10);
- }
- }
package com.kb.flyweight; import java.awt.Color; import java.awt.Graphics; public class TreeType { private String name; private Color color; public TreeType(String name, Color color) { this.name = name; this.color = color; } public void draw(Graphics g, int x, int y) { g.setColor(color); g.fillOval(x - 5, y - 10, 10, 10); } }
Step 3
Create a class TreeFactory which helps us to cache the similar trees
- package com.kb.flyweight;
- import java.awt.Color;
- import java.util.HashMap;
- import java.util.Map;
- public class TreeFactory {
- static Map<String, TreeType> treeTypes = new HashMap<>();
- //Create new TreeType only if not available in Map
- public static TreeType getTreeType(String name, Color color) {
- TreeType result = treeTypes.get(name);
- if (result == null) {
- result = new TreeType(name, color);
- treeTypes.put(name, result);
- }
- return result;
- }
- }
package com.kb.flyweight; import java.awt.Color; import java.util.HashMap; import java.util.Map; public class TreeFactory { static Map<String, TreeType> treeTypes = new HashMap<>(); //Create new TreeType only if not available in Map public static TreeType getTreeType(String name, Color color) { TreeType result = treeTypes.get(name); if (result == null) { result = new TreeType(name, color); treeTypes.put(name, result); } return result; } }
Step 4
Create a forest class which extends AWT Jframe
It will have list of trees
- package com.kb.flyweight;
- import java.awt.Color;
- import java.awt.Graphics;
- import java.util.ArrayList;
- import java.util.List;
- import javax.swing.JFrame;
- public class Forest extends JFrame {
- private List<Tree> trees = new ArrayList<>();
- public void plantTree(int x, int y, String name, Color color) {
- TreeType type = TreeFactory.getTreeType(name, color);
- Tree tree = new Tree(x, y, type);
- trees.add(tree);
- }
- @Override
- public void paint(Graphics graphics) {
- for (Tree tree : trees) {
- tree.draw(graphics);
- }
- }
- }
package com.kb.flyweight; import java.awt.Color; import java.awt.Graphics; import java.util.ArrayList; import java.util.List; import javax.swing.JFrame; public class Forest extends JFrame { private List<Tree> trees = new ArrayList<>(); public void plantTree(int x, int y, String name, Color color) { TreeType type = TreeFactory.getTreeType(name, color); Tree tree = new Tree(x, y, type); trees.add(tree); } @Override public void paint(Graphics graphics) { for (Tree tree : trees) { tree.draw(graphics); } } }
Step 5
Create a client program
- package com.kb.flyweight;
- import java.awt.Color;
- public class FlyweightClient {
- public static void main(String[] args) {
- Forest forest = new Forest();
- //Trying to create 1 lakh objects, but because of flyweight pattern,we will reuse and reduce the no of objects
- for (int i = 0; i < 100000; i++) {
- forest.plantTree(random(0, 200), random(0, 200), "Neem", Color.GREEN);
- forest.plantTree(random(0, 200), random(0, 200), "Banyan", Color.YELLOW);
- }
- forest.setSize(200, 200);
- forest.setVisible(true);
- System.out.println(100000 + " trees drawn");
- }
- private static int random(int min, int max) {
- return min + (int) (Math.random() * ((max - min) + 1));
- }
- }
package com.kb.flyweight; import java.awt.Color; public class FlyweightClient { public static void main(String[] args) { Forest forest = new Forest(); //Trying to create 1 lakh objects, but because of flyweight pattern,we will reuse and reduce the no of objects for (int i = 0; i < 100000; i++) { forest.plantTree(random(0, 200), random(0, 200), "Neem", Color.GREEN); forest.plantTree(random(0, 200), random(0, 200), "Banyan", Color.YELLOW); } forest.setSize(200, 200); forest.setVisible(true); System.out.println(100000 + " trees drawn"); } private static int random(int min, int max) { return min + (int) (Math.random() * ((max - min) + 1)); } }
We can see the output image, In that 100000 objects are displayed but because of Flyweight pattern
We have reused many objects and reduced the memory consumption.
When to use Flyweight pattern ?
When we need to create large number of similar objects
When memory is a constraint as more objects consumes more memory
When most of the object attributes can be shared and made external
Where this pattern currently used ?
valueOf() method of all wrapper classes in java