Design Patterns, Flyweight, Java, OOP, structural design patterns

Design Patterns: Flyweight

In this article, we are going to delve into another Structural Pattern and it is called Flyweight. Let’s start with the definition from Gang of Four Book.

[quote name=”GoF”]Facilitates the reuse of many fine-grained objects, making the utilization of large numbers of objects more efficient.[/quote]

Flyweight pattern is used to reduce the number of objects that are created. So, memory usage is decreased as well. Apart from that, a new keyword is not needed in order to create the same object again and again.

Every time that an object is created, it is stored, and if the same object is asked, then Flyweight gives it back to you. Otherwise, a new object is created and stored for future usage.

This pattern uses intrinsic and extrinsic properties.

What are intrinsic and extrinsic properties

Intrinsic properties help us make the object unique, whereas extrinsic properties are set by the client to perform a specific operation.

When do we have to use Flyweight Pattern

In case that we need to create many objects that are very similar and these objects cost a lot to be generated, it is a very good opportunity to reduce memory and increase performance by using the Flyweight Pattern.

Example

Let’s suppose that we are making a platform game. The star of the game has to kill all the enemies. Enemies are generated at the run time and they are very similar.

Using the new keyword in order to create a new enemy at the run time is too expensive. Our game is going to lack in memory and become slow if we are not careful.

It is time to create some enemies with the Flyweight design pattern.

We start with the Enemy interface.

The Next class implements the Enemy interface.

Let’s create different types of weapons.

It is time to create a Factory class. This class returns an existing enemy if an enemy of a given type exists. Otherwise, it creates a new enemy, stores it in hashTable for future usage, and returns it.

Let’s run an example.

Output:

You can download the source code from GitHub.