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
Start by examining the existing
Shape
,Circle
,ShapeFactory
, andFlyweightPatternDemo
classes.Create a
Rectangle
class that implements theShape
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 adraw
method that prints a message including the color, length, and breadth.
Modify the
ShapeFactory
class to manageRectangle
objects as well asCircle
objects.Add a new
HashMap
field for rectangle objects.Create a
getRectangle
method that accepts a color. If aRectangle
of that color exists, return it. If not, create a newRectangle
of that color, add it to theHashMap
, and then return it.
Update the
FlyweightPatternDemo
class to demonstrate the use ofRectangle
objects.Create a loop that creates 10 rectangle objects with random colors, lengths, and breadths, and calls the
draw
method on each one.
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).