Flyweight Design Pattern

What is Flyweight Design Pattern?

  • It is used to create a large number of objects of almost similar nature.
  • A large number of objects consume a large amount of memory.
  • Flyweight design pattern provides a solution for reducing the load on memory by sharing objects.
  • It is used to reduce the number of objects created and improve performance.
  • It reuses the already existing similar kind of objects and creates a new object when no matching object is found.
  • Intrinsic states are the constants and are stored in memory.
  • Extrinsic states are not constants and need to be calculated on the fly and they are not stored in memory.

Table of Contents

Real Life Examples of Flyweight Design Pattern

Example 1:

printout sample photoFor example, Let’s suppose if you need some thousand copies of some data. There are two ways to achieve that.The first approach, we can get the printouts for 1000 times. The second approach, we can get a printout of that data and then we can use that printout and then we can take 999 photocopies.Let’s suppose if the printout for one copy is 2 Rupees, then the total amount required is 1000*2=2000RS. If the photocopy is 1 Rupee, then the total amount required is 999*1=999RS and one printout so totally 1001 Rupees.So we can save much amount if we could follow the second approach.

Example 2:

angry bird sample photoLet’s consider a second example; you might have played Angry Birds game. We can relate this game with Flyweight Design Pattern. In this game, most of the bird animations are of similar base features like size, nose, eyes, hair, etc.If we require a similar kind of object, for example, we need this Angry birdbut of red color. Then what we can do is, we can use this object from the cache and then we can apply the red color on the fly. So this is the power of Flyweight Design Pattern. So we can create many objects of this similar kind without expanding the memory at the run time. So here we are reusing the object, but we are applying the additional features on the fly.So that’s the point.It uses the already existing similar kind of object and creates a new object when no object exists.

Advantages of Flyweight Design Pattern

  • Flyweight Design Pattern saves memory because it reuses the existing objects.
  • It provides a solution for reducing the load on memory by sharing objects.
  • It improves the overall performance because the object creations are reduced.

UML Class Diagram of Flyweight Design Pattern

Flyweight Design Pattern Java Implementation

Step 1:

public interface Shape
    public void draw();

Step 2:

public class Circle implements Shape

    private String color;
    private int x;
    private int y;
    private int radius;

    public Circle(String color)
        this.color = color;

    public void setX(int x)
        this.x = x;

    public void setY(int y)
        this.y = y;

    public void setRadius(int radius)
        this.radius = radius;

    public void draw()
        System.out.println("Circle: Draw() [Color : " + color + ", x : " + x + ", y :" + y + ", radius :" + radius);

Step 3:

public class ShapeFactory

    private static final HashMap cricleCache = new HashMap();

    public static Shape getCircle(String color)
        Circle circle = (Circle) cricleCache.get(color);

        if (circle == null)
            circle = new Circle(color);
            cricleCache.put(color, circle);
            System.out.println("There is no cached object so Creating circle of color : " + color);
        return circle;

Step 4:

public class FlyWeightEX {private static final String colors[] = { “Red”, “Green”, “Blue”, “White”, “Black” };public static void main(String[] args) {for (int i = 0; i < 10; ++i) { String targetColor=getRandomColor(); System.out.println("Target color: "+targetColor); Circle circle = (Circle) ShapeFactory.getCircle(targetColor); circle.setX(getRandomX()); circle.setY(getRandomY()); circle.setRadius(50); circle.draw(); } }private static String getRandomColor() { return colors[(int) (Math.random() * colors.length)]; }private static int getRandomX() { return (int) (Math.random() * 100); }private static int getRandomY() { return (int) (Math.random() * 100); }} [/code]