Java flyweight design pattern comes under structural design patterns and it is used to reduce number of object creation by reusing the existing similar objects. Only create a new object if there is no matching object.

Main advantage of flyweight design pattern is that, it reduces memory consumption by controlling the amount object creation.

Let’s discuss flyweight design pattern by below example. We are going to create 10 Rectangle with different colors but will restrict the object creation. Max 3 objects will be created.

Output

Creating circle of color : Blue
Rectangle created with following properties:Color: Blue
Length:0
Width:43
Creating circle of color : Red
Rectangle created with following properties:Color: Red
Length:6
Width:9
Creating circle of color : Green
Rectangle created with following properties:Color: Green
Length:24
Width:24Rectangle created with following properties:Color: Green
Length:68
Width:26Rectangle created with following properties:Color: Blue
Length:54
Width:34Rectangle created with following properties:Color: Green
Length:92
Width:58Rectangle created with following properties:Color: Blue
Length:12
Width:31Rectangle created with following properties:Color: Blue
Length:56
Width:0Rectangle created with following properties:Color: Blue
Length:43
Width:27Rectangle created with following properties:Color: Blue
Length:40
Width:80