Core Java

Java Flyweight Design Pattern Example

1. Introduction

In this article, we will look at the Java flyweight design pattern. This design pattern helps us to reduce the memory usage. It can also improve performance in applications where object attachment is costly. The main intent of Flyweight design pattern is “Facilitates the reuse of many fine grained objects and makes the use of large numbers of objects more efficient.”. In other words the Flyweight pattern explains how objects can be distributed so that they can be used without restrictive costs in fine granules. In software development each ” flyweight ” object is categorised into two parts: the (extrinsic) state – dependent part and the (intrinsic) state – independent part. So, the intrinsic state of the Flyweight object is stored (shared) whereas extrinsic state is stored or computed by user objects and invoked to the Flyweight object.

When implementing design patterns, A pattern or design pattern is a written documentation in application development that describes a common solution to a design issue, which frequently take place in more than one projects. The designers of application reshape the design solution to their specific project. Design patterns use a traditional perspective to describe a design problem, its solution presented and any other factors that could have an effect on the problem or the solution.

2. Java Design Patterns

In general there are principally three types of design patterns in the core java, which are further divided into their sub-parts:

  1. Creational patterns
  2. Structural patterns
  3. Behavioural patterns

2.1 Creational Pattern

All of these design patterns relate to class instantiation or object creation. These design patterns can also be classified into class-creation patterns and object-creation patterns. When dealing with class creation pattern and object creation pattern, The class creation patterns effectively use inheritance in the installation process whereas object creation patterns effectively use delegation to get the work done.

Factory Method Pattern, Abstract Factory Pattern, Builder Pattern, Singleton Pattern, Object Pool Pattern and Prototype Pattern are Creational design patterns.

2.2 Structural Pattern

Structural design patterns organise different classes and objects to create larger structures and offer new features. These design patterns generally work with relationships between classes and objects, so that they can work together more easily. In simple words, these design patterns consider class and object composition. Concept of inheritance is used to formulate interfaces and interpret ways to manufacture objects to obtain polished functionalities.

Adaptor Pattern, Bridge Pattern, Composite Pattern, Decorator Pattern, Facade Pattern, Flyweight Pattern, Private Class Data Pattern and Proxy Pattern are structural design patterns.

2.3 Behavioural Pattern

Behavioural design patterns are roughly identifying common communication patterns surrounded by objects and understand these patterns. In short, Behavioural patterns are used in communications between entities and the way one sees it easier and in a superior way flexible for these entities to communicate.

Behavioural design patterns such as Chain of responsibility Pattern, Command Pattern, Interpreter Pattern, Iterator Pattern, Mediator Pattern, Memento Pattern, Null Object pattern, Observer Pattern, State Pattern, Strategy Pattern, Template Pattern, Visitor Pattern.

Below, we will explore the easiest but most commonly been using structural design patterns–the Flyweight design pattern. This article presents the concept of the Flyweight design pattern with a real-world example to help you fully understand how the Flyweight design pattern enables software developers deliver a better software application. The aspects below this develop this pattern thematically in order to better understand each part of the Flyweight design pattern. We will therefore introduce the Flyweight design pattern in Java code.

3. Understanding the Flyweight design pattern

In this section we will understand Flyweight design pattern in detail. So, The Flyweight design pattern can be used exclusively to lower the number of generated objects and even eliminate memory density and increase performance. This particular type of design pattern is structural in nature even though this pattern wants to offer ways to minimise the range of objects and even to strengthen the architecture of the object of the application.

However in the Flyweight pattern, we have used a Hash-map that stores references to the already created object, each and every object is associated with a key. If a client wanted to create an object, he simply moves a key normally associated with it unless the object is already being created, we simply just get the direct reference to that object, otherwise it introduces a new object and then reverts it to the client.

Sometimes we really have to think about intrinsic and extrinsic data when you look at this pattern. We must divide the object property into intrinsic and extrinsic data to apply the Flyweight design pattern. The intrinsic data is the data which makes this object unique. Extrinsic data however is the information available which can be easily passed through the arguments. Therefore, when we can render some extrinsic data for instances where you have a huge number of objects, the Flyweight design pattern can be pretty much exactly what you want. Sometimes we really will have to actually think about intrinsic and extrinsic data when you take a look at this pattern.

Let ‘s take a look at the UML class diagram to understand the Flyweight design pattern before going into more detail.

Java Flyweight Design Pattern - UML Class diagram
UML Class diagram

The diagram above consists of classes, interfaces and objects described below:

  • Flyweight: The Flyweight interface concludes methods for obtaining and using extrinsic data from flyweight instances.
  • FlyweightFactory: The FlyweightFactory class is entirely responsible for developing and managing flyweights, guaranteeing that they have been properly shared. If the desired flyweight is still not created, it will generate one and revert back one. If not, it will restore one from the present flyweight bucket.
  • ConcreteFlyweight: ConcreteFlyweight class adds another layer intrinsic state capabilities. In this class the flyweight object must also be shareable.
  • UnsharedConcreteFlyweight: The UnsharedConcreteFlyweight represents a way that use this pattern even without implementing the common idea encouraged by the interface. However, many uses of this pattern includes shareable flyweights.

3.1 Real Life Example

Now, in this portion we will discuss Flyweight design pattern using a real world example – Angry birds game. Angry birds is one of the most entertaining and trending game now a days and most of the people loved to play this game on daily basis. Let us see how we can implement flyweight pattern with the help of this game. In Angry birds game assume, if we want to create 20000 red colour angry bird what we will do is that we will create 20000 angry bird object and fill it with red colour. So, if we create 20000 object then it will occupy more memory and affect the performance of the game so to avoid this complexity we can do one thing that according to Flyweight design pattern we can create only one object without any colour and pushes into Hash-map.

Flyweight design pattern - Real life example
Flyweight design pattern – Real life example

So, what happen whenever we need angry bird object we can get this object from the Hash-map and can fill the colour so in this way we no need to create 20000 or more angry bird objects but we have to create just one angry bird object without any colour and this way we can improve the performance. Suppose, if we want to create 30000 blue colour angry bird then we can get the angry bird object from the the Hash-map and fill that object with blue colour. In Flyweight design pattern there are to states intrinsic state and extrinsic state. In this example angry bird objects is an intrinsic state and colour of angry bird is an extrinsic state.

4. Implementing Flyweight design pattern

So in this portion we implement flyweight design pattern in the java program using the real word example-Angry birds which was mentioned above.

Bird.java

public interface Bird {
   void draw();
}

In the above code we have created an interface called bird in which we have defined a method draw().

AngryBird.java

public class AngryBird implements Bird {
	   private String color;


	   public AngryBird(String color){
	      this.color = color;		
	   }

	   @Override
	   public void draw() {
	      System.out.println("Angry Bird: Draw() [Color : " + color);
	   }
	}

In above code we have created a class AngryBird which implements Bird interface. In this class we created a private object color and AngryBird() method. Also we have implemented draw() method which was defined in Bird interface.

BirdFactory.java

import java.util.HashMap;

public class BirdFactory {

	   private static final HashMap angrybirdMap = new HashMap();

	   public static Bird getAngryBird(String color) {
	      AngryBird angrybird = (AngryBird)angrybirdMap.get(color);

	      if(angrybird == null) {
	    	  angrybird = new AngryBird(color);
	    	  angrybirdMap.put(color, angrybird);
	         System.out.println("Creating Angry Bird of color : " + color);
	      }
	      return angrybird;
	   }
	}

In the above code we have implemented BirdFactory class in which we implemented a getAngryBird() method. BirdFactory has a HashMap of AngryBird having key as color of the AngryBird object. Whenever a request comes to create a angry bird of particular color to BirdFactory, it checks the angrybird object in its HashMap, if object of AngryBird found, that object is returned otherwise a new object is created, stored in hashmap for future use, and returned to client.

FlyweightDesignPattern.java

public class FlyweightDesignPattern {
	  private static final String colors[] = { "Red", "Orange", "Blue", "Yellow", "Pink" };
	   public static void main(String[] args) {

	      for(int i=0; i < 20; ++i) {
	    	 AngryBird angrybird = (AngryBird)BirdFactory.getAngryBird(getRandomColor());
	    	 
	    	 angrybird.draw();
	      }
	   }
	   private static String getRandomColor() {
	      return colors[(int)(Math.random()*colors.length)];
	   }

}

In the above code we have created FlyweightDesignPattern class in which we have defined an array of colors and it consists of main() method. FlyweightDesignPattern, our main class, will use BirdFactory to get a Bird object. It will pass information (red / Orange / blue / Yellow / Pink) to BirdFactory to get the Angry Bird of desired color it needs.

5. Benefits of using Flyweight Design Pattern

So far we have explored very well what the Flyweight design pattern is, its full implementation using the java code and also the knowledge of the Flyweight design pattern diagram as well as its real life example. So now, let’s start talking over some of its benefits. The main benefits of Flyweight design pattern are as follows:

  • Flyweight design pattern has an important benefit that it lowers the number of objects. If we want to create 10000 circles than using this design pattern only we have to create one circle object and stores into Hash-map. Then when needed we can get this object from the Hash-map and use it any number of times.
  • Another benefit of this pattern is that it reduces the amount of required memory and storage devices if the objects are continued. Instead of creating 10000 object we have to create only one object and push into Hash-map due to this it reduces usage of memory.
  • Flyweight design pattern decreases the earlier system strain caused mostly by the initialisation of all objects in the collection.

6. Use of Flyweight Design Pattern

Flyweight design pattern is used when many objects in a class need to be created. Though each object absorbs memory space that can become critical for relatively low memory devices, like smartphones and tablets or embedded systems, flyweight design patterns can also be used to limit memory loads by sharing objects. Other usage of Flyweight design pattern are elaborate below:

  • In software development, whenever an application uses or needs many numbers of object (For example, 10000 object) Flyweight design pattern takes place in this development.
  • This design pattern is also used  when the memory and storage cost is more because of the quantity of objects (For example, 10000 object). Because in this pattern we use Hash-map to store the created object that will be used many times.
  • In application development, Flyweight design pattern is used when the application does not depend on object identity.
  • This pattern is also used when the object properties can be classified into intrinsic and extrinsic properties and the client application should define the extrinsic properties of an object.

7. Demerits of Flyweight Design Pattern

However, there are disadvantages that we should be aware of when applying the Flyweight design pattern.

  • One of the main disadvantages of this pattern is that all class objects are connected, so that only one class object can not be independent of other instances.
  • Flyweight design pattern can cause disruptions that can take place better during the earlier load if a vast number of objects are required at once.
  • If this design pattern is badly designed, the the software architecture can be significantly complicated, because it adopts many small but identical objects into our namespace.

8. Java Flyweight Design Pattern – Conclusion

Hence it is concluded that Flyweight pattern seeks to improve overall performance by establishing many objects from a limited set of objects, where all these objects are the same or very identical to all other objects. However in reality, the utility of this pattern is restricted and you can use this Design pattern better. Some may find that the Flyweight design pattern is complex, and I agree it will be one of the least used design patterns. And it is undoubtedly less used because computer systems are now more powerful. When this design pattern finally comes to huge software development, the Flyweight design takes place and this will save system resources. The Flyweight design pattern encourages the separation of multi-functional systems from the extrinsic data.

9. Download the Source Code

The above written java program can be downloaded from the below link.

Download
You can download the full source code of this example here: FlyweightDesignPattern.zip

Abhishek Kothari

Abhishek is a Web Developer with diverse skills across multiple Web development technologies. During his professional career, he has worked on numerous enterprise level applications and understood the technological architecture and complexities involved in making an exceptional project. His passion to share knowledge among the community through various mediums has led him towards being a Professional Online Trainer, Youtuber as well as Technical Content Writer.
Subscribe
Notify of
guest

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

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
rajasekhar
rajasekhar
5 years ago

Thanks,

Why can’t we create a single Bird with draw(color) method and call multiple times same bird object by passing color. Why we need to create this much complicate structure.

Back to top button