Flyweight Pattern Demo

package FlyweightPatternDemo; interface Shape { void draw(); }
package FlyweightPatternDemo; 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); } }
package FlyweightPatternDemo; import java.util.HashMap; class ShapeFactory { private static final HashMap<String, Shape> circleMap = new HashMap<>(); public static Shape getCircle(String color) { Circle circle = (Circle)circleMap.get(color); if(circle == null){ circle = new Circle(color); circleMap.put(color, circle); System.out.println("Creating circle of color : " + color); } return circle; } }

Driver

We will draw circles of different colors, but we will only create a new circle if a circle of that color doesn't exist yet.

As you can see, the ShapeFactory class uses a HashMap to store references to the Circle objects. This allows the ShapeFactory to return an existing Circle if one of the same color already exists or to create a new one if necessary.

Remember that flyweight pattern should be used when the number of objects is high, their storage cost is high, they are immutable, and the identity of the individual objects is not important for your application.