Design Patterns Flyweight Pattern - Design Patterns

What is Design Patterns Flyweight Pattern?

Flyweight pattern is mainly used to decrease the integer of objects created and to decrease memory path and increase performance. This type of design pattern comes under structural pattern as this pattern provides ways to decrease object count thus getting better the object arrangement of request.

Flyweight pattern tries to discard already existing related kind objects by storing them and creates new object when no matching object is found. We will demonstrate this pattern by drawing 20 circles of similar locations but we will create only 5 objects. Only 5 colours are available so colour property is used to check already active Circle objects.


We are going to create a Shape interface and concrete class Circle implementing the Shape interface. A factory class Shape works is define as a subsequently step.

Shape Factory has a Hash Map of Circle having key as colour of the Circle article. Whenever a request comes to create a circle of particular colour to Shape Factory, it checks the circle object in its Hash Map, if object of Circle establish, that object is returned otherwise a new entity is created, stored in hash map for future use, and return to client.

FlyWeightPatternDemo, our demo class, will use Shape Factory to get a Shape object. It will exceed in order (red / green / blue/ black / white) to Shape plant to get the circle of desired colour it wants.
flyweight_pattern_uml_diagram (1)

Step 1

Create an interface.

Step 2

Make concrete class implementing the same interface.

Step 3

Create a factory to generate object of concrete class based on given information.

Step 4

Use the works to get object of concrete class by momentary information such as colour.

Step 5

Verify the output.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

Design Patterns Topics