What is Flyweight pattern? Explain with example.
What is Flyweight pattern? Explain with example.
Flyweight is a structural pattern that is used when there is a need to create large number of similar objects. It reduces the number of objects created thereby decreasing memory footprint and increasing performance. Flyweight pattern try to reuse already existing similar kind objects by storing them and creates new object when no matching object is found. Factory pattern and Singleton pattern are used in implementing Flyweight pattern. Let us understand this with an example.
This example reuses the Factory pattern example discussed earlier.
ShapeType is an enum, Shape is an abstract class which has Square and Rectangle as concrete classes. The Flyweight pattern is demonstrated with the FlyweightShapeFactory class as below. The FlyweightShapeFactory class is our Flyweight factory. It utilizes the singleton pattern so that we only have once instance of the factory. The FlyweightShapeFactory creates an EnumMap pool of shapes which stores all the instances of the different types of shapes. Only one instance of each type is created, and this occurs on-demand.
public class FlyweightShapeFactory { private static FlyweightShapeFactory factory = null; private Map<ShapeType, Shape> instancePool = null; private Shape shape = null; private FlyweightShapeFactory() { instancePool = new EnumMap<ShapeType, Shape>(ShapeType.class); } public static FlyweightShapeFactory getInstance() { if (factory == null) { factory = new FlyweightShapeFactory(); } return factory; } public Shape createShape(ShapeType shapeType) { if (instancePool.containsKey(shapeType)) { return instancePool.get(shapeType); } switch (shapeType) { case SQUARE: shape = new Square(); break; case RECTANGLE: shape = new Rectangle(); break; } instancePool.put(shapeType, shape); return shape; } }
/* This can be tested with the below code. When we test this, we see that it creates the Shape object first time and reuse from next time instead of creating new objects */
public class TestFlyweight { public static void main(String arg[]) { FlyweightShapeFactory factory = FlyweightShapeFactory.getInstance(); for (int index = 0; index < 5; index++) { Shape shape = factory.createShape(ShapeType.SQUARE); shape.displayShapeInfo(); shape = factory.createShape(ShapeType.RECTANGLE); shape.displayShapeInfo(); } } }