Flyweight Pattern in Java

by | Sep 28, 2020 | Java

Home » Java » Flyweight Pattern in Java

Flyweight Pattern is a memory-efficient JAVA design pattern that is an integral part of structural design patterns. This pattern is used in a code that requires a huge number of objects to be created. As the name suggests, objects created using this pattern (generally referred to as flyweight objects) take up as less memory as possible thereby freeing up space for other objectives and functions to be performed. The main goal of the flyweight pattern is to reduce the number of objects that are being created and decrease memory footprint.

Definition

By definition, Flyweight Pattern reduces the memory occupied by each object thereby making the code efficient and increasing the speed and usability of existing objects. More the number of objects in a code, the more complexity it brings with it along with errors like OutofMemoryError exceptions.

How are Objects reduced?

To decrease the object count and save memory, the Flyweight pattern tries to reuse objects that match the requirement of the current instantiation by storing them. It creates a new object when the required attributes do not match with the stored objects. Conventionally, a HashMap is used to store the object references where every key of the HashMap points to a particular stored object. Clients can also access objects in the same manner with the help of the keys.

Example and Code

Let us a consider a pencil manufacturing factory that produces pencils of various shades.

//Let us create a pencil interface
public interface Pencil {
public manufacture ();
public Shade getShade();
//Now we will make a concrete class that will implement the interface.
public class Camlin implements Pencil {
private Shade shade;
// Now let us implement the pencil factory that will create one pencil object for each shade. The objects will then be stored in a Hash Map.
public PencilFactory implements Pencil {
private static Map <Shade, Pencil> pencilStore = new HashMap<>();
public static Pencil newPencil (Shade shade) {
Pencil pencil = pencilStore.computeIfAbsent (shade, newShade ->)
return new Camlin (newShade);
}
return newPencil;
}

When to Use the Flyweight Pattern?

This method can and should be used in all general programs written in JAVA as it makes the code efficient. Specifically speaking, this code proves to be beneficial when there is memory shortage and you have to run a program that wants to create several objects at a time.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author