For 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.
Let’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.
public interface Shape { public void draw(); }
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; } @Override public void draw() { System.out.println("Circle: Draw() [Color : " + color + ", x : " + x + ", y :" + y + ", radius :" + radius); } }
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; } }