Flyweight Pattern Lab

Objective

In this lab, you will practice implementing the Flyweight design pattern in Java. You will modify an existing application that creates circle objects to also create rectangle objects. You will observe how the Flyweight pattern is used to conserve memory by sharing objects with the same intrinsic state between different clients.

Instructions

  1. Start by examining the existing Shape, Circle, ShapeFactory, and FlyweightPatternDemo classes.

  2. Create a Rectangle class that implements the Shape interface.

    • The Rectangle class should contain fields for color (String), length (int), and breadth (int).

    • The Rectangle class should have a constructor that accepts a color and sets the color field.

    • The Rectangle class should have methods to set the length and breadth.

    • The Rectangle class should have a draw method that prints a message including the color, length, and breadth.

  3. Modify the ShapeFactory class to manage Rectangle objects as well as Circle objects.

    • Add a new HashMap field for rectangle objects.

    • Create a getRectangle method that accepts a color. If a Rectangle of that color exists, return it. If not, create a new Rectangle of that color, add it to the HashMap, and then return it.

  4. Update the FlyweightPatternDemo class to demonstrate the use of Rectangle objects.

    • Create a loop that creates 10 rectangle objects with random colors, lengths, and breadths, and calls the draw method on each one.

  5. Test your application to ensure that it behaves as expected.

    • Run your application and observe the output. Ensure that it creates a new object only when a rectangle of that color does not exist yet.

    • Note the way the Flyweight pattern is used to save memory.

Bonus

If you have extra time, consider these additional tasks:

  • Add another shape to your application (like a square, triangle, etc.) and modify your ShapeFactory to handle this additional shape.

Thoughts

  • Remember that the Flyweight pattern should be used when you have a large number of objects that consume a lot of memory, and the majority of the object data can be made extrinsic.

  • In the context of the Flyweight pattern, intrinsic data is the data that is shared across the objects (like color), and extrinsic data is the data that varies between the objects (like the location, length, breadth).