Flyweight Design Pattern

Introduction

 
In this post, we will talk about Flyweight design pattern. We will see when one should use this design pattern and how we can implement it. In the below example, we will use C# language to implement the example. 
 

Description

 
In early days of computing, memory was very costly, but nowadays, it's getting cheaper on a daily basis. Usually, in software application, memory is needed to create and hold objects. Sometimes, some objects stay in memory for a longer period of time. It's the developer’s responsibility to remove the object from memory whenever it's not needed to save memory. Another way to save memory is to use a created object instead of creating a new object each time. This will definitely save memory and improve the performance of the application.
 
To achieve this, we should have a pool of objects where we will keep all newly created objects. Whenever we need the same object, we will query to pool and get that object. After query, if the needed object doesn’t exist in the pool, we will create new one and store it in the pool. In a higher language like C# or Java, we can use Dictionary<Key,Value> or HashTable<Key,Value> to create a pool.
 
Example
 
Let's add new project. You can give any name you want to it.
 
 
 
Lets create a contract called “IShape” which will be implemented by different shapes.
  1. internal interface IShape  
  2.     {  
  3.         void Print();  
  4.     }  
Lets add a “Rectangle” shape.
  1. internal class Rectangle : IShape  
  2.     {  
  3.         public void Print()  
  4.         {  
  5.             Console.WriteLine("Printing Rectangle");  
  6.         }  
  7.     }  
Lets add a “Circle” shape.
  1. internal class Circle : IShape  
  2.     {  
  3.         public void Print()  
  4.         {  
  5.             Console.WriteLine("Printing Circle");  
  6.         }  
  7.     }  
Lets add “Shapes” enum.
  1. public enum Shapes  
  2.     {  
  3.         Rectangle,  
  4.         Circle  
  5.     }  
Here's a factory class which will hold all objects in dictionary (hashtable). If the requested object doesn't exist in this list, then it will create it, or else it will return the already created one. 
  1. internal class ShapeObjectFactory  
  2.     {  
  3.         private readonly Dictionary<Shapes, IShape> shapes = new Dictionary<Shapes, IShape>();  
  4.   
  5.         public int TotalObjectsCreated  
  6.         {  
  7.             get { return shapes.Count; }  
  8.         }  
  9.   
  10.         public IShape GetShape(Shapes shapeType)  
  11.         {  
  12.             IShape shape = null;  
  13.             if (shapes.ContainsKey(shapeType))  
  14.             {  
  15.                 shape = shapes[shapeType];  
  16.             }  
  17.             else  
  18.             {  
  19.                 switch (shapeType)  
  20.                 {  
  21.                     case Shapes.Rectangle:  
  22.                         shape = new Rectangle();  
  23.                         shapes.Add(Shapes.Rectangle, shape);  
  24.                         break;  
  25.   
  26.                     case Shapes.Circle:  
  27.                         shape = new Circle();  
  28.                         shapes.Add(Shapes.Circle, shape);  
  29.                         break;  
  30.   
  31.                     default:  
  32.                         throw new Exception("Factory cannot create the object specified");  
  33.                 }  
  34.             }  
  35.             return shape;  
  36.         }  
  37.     }  
Client program
  1. internal class Program  
  2.     {  
  3.         private static void Main(string[] args)  
  4.         {  
  5.             var factoryObject = new ShapeObjectFactory();  
  6.   
  7.             IShape shape = factoryObject.GetShape(Shapes.Rectangle);  
  8.             shape.Print();  
  9.             shape = factoryObject.GetShape(Shapes.Rectangle);  
  10.             shape.Print();  
  11.             shape = factoryObject.GetShape(Shapes.Rectangle);  
  12.             shape.Print();  
  13.   
  14.             shape = factoryObject.GetShape(Shapes.Circle);  
  15.             shape.Print();  
  16.             shape = factoryObject.GetShape(Shapes.Circle);  
  17.             shape.Print();  
  18.             shape = factoryObject.GetShape(Shapes.Circle);  
  19.             shape.Print();  
  20.   
  21.             int NumObjs = factoryObject.TotalObjectsCreated;  
  22.             Console.WriteLine("\nTotal No of Objects created = {0}", NumObjs);  
  23.             Console.ReadKey();  
  24.         }  
  25.     }  
Execution of simple program:
 

Conclusion

 
Advantages
  1. We should use this design pattern when we need to create large number objects.
  2. Reduces memory usage by sharing heavy objects.
Here is the full code on Github. Feel free to clone the repo: Flyweight design pattern repo
 
Happy coding!