Flyweight Design Pattern

 The Flyweight Design Pattern is one of the structural patterns introduced by the GOF. The Flyweight Pattern is about creating a pool of objects that allows sharing already existing objects and causing the application to consume less memory.

So this pattern does the following two things because the pattern creates objects once and then saves them to a pool:
  1. Increases application performance in terms of object creation since there is no requirement of creating an object for every request.

  2. Causes the application to consume less memory, since the object already exists in memory and no new object must be created because of the pool.

Ultimately flyweight patterns make the application efficient in terms of memory and processing.

Basic UML class Diagram of Design Pattern

The following image shows the class diagram of the basic Flyweight Design Pattern.

UML class Diagram

  • IFlyweight: Basic contract to be implemented by derived types, in other words by concrete flyweight.

  • FlyweightFactory: It's a factory class used by a client class to get the data from the concreate flyweight. This class is also responsible for creating the pool of an existing object. So when the request for data come that is already requested it returns data from the pool.

  • ConcerateSharedFlyweight1: It's a concreate implementation of the flyweight interface. As the name suggests, an object returned by this class will be shared among the clients of it.

  • ConcerateUnSharedFlyweight1: It's a concreate implementation of the flyweight interface. As the name suggests an object returned by this class will be unshared. That means that every time the client requires a new object.

  • Client: uses the concreate implementation, it creates an instance of Decorate and uses the functionality of it.

Note: UnSharedFlyweight is not always required, it depends on requirements, but SharedFlyweight is always required when you use the flyweight pattern.

The following code is the implementation of the Flyweight Design Pattern and the Class Diagram was shown above.

  1. namespace BasicFlyweightPattern  
  2. {  
  3.     #region basic implementation  
  4.     public class FlyweightFactory   
  5.     {  
  6.         public static List<Item> GetStaticItemList(string key)  
  7.         {  
  8.             IFlyWeight flyWeight = null;  
  9.             ICacheManager _objCacheManager = CacheFactory.GetCacheManager();  
  10.   
  11.             if (key == "A")  
  12.             {  
  13.                 if (_objCacheManager.Contains("A"))  
  14.                 {  
  15.                     return _objCacheManager["A"as List<Item>;  
  16.                 }  
  17.                 else  
  18.                 {  
  19.                     flyWeight = new ConcerateSharedFlyweight1();  
  20.                 }  
  21.             }  
  22.             else if (key == "B")  
  23.             {  
  24.                 if (_objCacheManager.Contains("B"))  
  25.                 {  
  26.                     return _objCacheManager["B"as List<Item>;  
  27.                 }  
  28.                 else  
  29.                 {  
  30.                     flyWeight = new ConcerateSharedFlyweight2();  
  31.                 }  
  32.             }  
  33.   
  34.             var list = flyWeight.GetList();  
  35.             _objCacheManager.Add(key, list);  
  36.             return list;  
  37.         }  
  38.     }  
  39.   
  40.     interface IFlyWeight  
  41.     {  
  42.         List<Item> GetList();  
  43.     }  
  44.   
  45.     public class Item  
  46.     {  
  47.         public int id { getset; }  
  48.         public string desc { getset; }  
  49.     }  
  50.   
  51.     public class ConcerateSharedFlyweight1 : IFlyWeight  
  52.     {  
  53.         private List<Item> ItemList;  
  54.   
  55.         public ConcerateSharedFlyweight1()  
  56.         {  
  57.             ItemList = new List<Item>();  
  58.         }  
  59.   
  60.         public List<Item> GetList()  
  61.         {  
  62.             ItemList.Add(new Item { id = 1, desc = "A1" });  
  63.             ItemList.Add(new Item { id = 2, desc = "A2" });  
  64.             ItemList.Add(new Item { id = 3, desc = "A3" });  
  65.             return ItemList;  
  66.         }  
  67.     }  
  68.   
  69.     public class ConcerateSharedFlyweight2 : IFlyWeight  
  70.     {  
  71.         private List<Item> ItemList;  
  72.   
  73.         public ConcerateSharedFlyweight2()  
  74.         {  
  75.             ItemList = new List<Item>();  
  76.         }  
  77.   
  78.         public List<Item> GetList()  
  79.         {  
  80.             ItemList.Add(new Item { id = 1, desc = "B1" });  
  81.             ItemList.Add(new Item { id = 2, desc = "B2" });  
  82.             ItemList.Add(new Item { id = 3, desc = "B3" });  
  83.             return ItemList;  
  84.         }  
  85.     }  
  86.   
  87.     class Program  
  88.     {  
  89.         static void Main(string[] args)  
  90.         {  
  91.             List<Item> list =FlyweightFactory.GetStaticItemList("A");  
  92.      //List<Item> list = FlyweightFactory.GetStaticItemList("B");              
  93.      foreach (var item in list)  
  94.             {  
  95.                 Console.WriteLine(item.id.ToString() + "  " + item.desc );  
  96.            }  
  97.   
  98.             Console.ReadLine();  
  99.         }  
  100.     }  
  101.   
  102. }  
The following are points to remember about the preceding code implementation:
  1. The client asks for data from FlyweightFactory by calling GetStaticItemList and passing the key as argument for getting the data.

  2. FlyweightFactory has a static method GetStaticItemList that creates an instance of concrete and gets data if the request is for the first time, for a later request it returns an existing object.

  3. FlyweightFacotry maintains a pool of existing objects using an Enterprise library caching block for sharing data among the clients, in other words different objects.

  4. In the concrete implementation of flyweight, a hardcoded list is returned but in an actual scenario this will be replaced by data from a data source.

  5. Item is a poco class, the list of which is returned from flyweight concrete classes. This class is represented by different items. The following actual scenario provides more detail.

Output

run

Here the output shows the result of A's same will use the result of B's. If the call comes a second time then the data is retuned from the cache.

Flyweight Design Pattern Example In an Actual Application

Problem Statement

A web application having a dropdown for displaying a list of Country, displaying a list of State, displaying a list of Product and so on in the dropdown and the dropdowns are part of multiple screens that are accessed by multiple users.

In this scenario, to display another kind of list for multiple user requests, the server must connect with the database server multiple times. This reduces the performance of the application and also consumes memory for creating and storing these lists.

Solution

The solution to the preceding problem is to use the Flyweight Design Pattern.

The following is a class diagram of the Flyweight pattern used in the application.

class diagram

  • Mapping with Basic Implementation.
  • IFlyweightManager is equals to IFlyweight.
  • StaticDataListFlyweightFactory is equal to FlyweightFactory.
  • CountryStaticListManager and ProductStaticListManager is equal to ConcerateSharedFlyweight1 and ConcerateSharedFlyweight2.
  • StaticItem is equal to Item.
  1. namespace FlyWeightPattern  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.   
  8.             List<StaticItem> countrylist = StaticDataListFlyWeidhtFactory.GetStaticItemList("Country");  
  9.             foreach (var item in countrylist)  
  10.             {  
  11.                 Console.WriteLine(item.id.ToString() + "  " + item.Code + "  " + item.Description);  
  12.             }  
  13.   
  14.             Console.ReadLine();  
  15.         }  
  16.     }  
  17.     public class StaticDataListFlyWeidhtFactory  
  18.     {  
  19.         public static List<StaticItem> GetStaticItemList(string key)  
  20.         {  
  21.             IFlyWeightManager manager = null;  
  22.             ICacheManager _objCacheManager = CacheFactory.GetCacheManager();  
  23.   
  24.             if (key == "Country")  
  25.             {  
  26.                 if (_objCacheManager.Contains("Country"))  
  27.                 {  
  28.                     return _objCacheManager["Country"as List<StaticItem>;  
  29.                 }  
  30.                 else  
  31.                 {  
  32.                     manager = new CountryStaticListManager();  
  33.                 }  
  34.             }  
  35.             else if (key == "ProductType")  
  36.             {  
  37.                 if (_objCacheManager.Contains("ProductType"))  
  38.                 {  
  39.                     return _objCacheManager["ProductType"as List<StaticItem>;  
  40.                 }  
  41.                 else  
  42.                 {  
  43.                     manager = new ProductTypeStaticListManager();  
  44.                 }  
  45.             }  
  46.   
  47.             var list = manager.GetList();  
  48.             _objCacheManager.Add(key, list);  
  49.             return list;  
  50.         }  
  51.     }  
  52.   
  53.     interface IFlyWeightManager  
  54.     {  
  55.         List<StaticItem> GetList();  
  56.     }  
  57.   
  58.     public class CountryStaticListManager : IFlyWeightManager  
  59.     {  
  60.         private List<StaticItem> StaticItemList;  
  61.   
  62.         public CountryStaticListManager()  
  63.         {  
  64.             StaticItemList = new List<StaticItem>();  
  65.         }  
  66.   
  67.         public List<StaticItem> GetList()  
  68.         {  
  69.             StaticItemList.Add(new StaticItem { id = 1, Code = "IND", Description = "India" });  
  70.             StaticItemList.Add(new StaticItem { id = 2, Code = "SRL", Description = "Sri Lanka" });  
  71.             StaticItemList.Add(new StaticItem { id = 3, Code = "SA", Description = "South Africa" });  
  72.             return StaticItemList;  
  73.         }  
  74.     }  
  75.   
  76.     public class ProductTypeStaticListManager : IFlyWeightManager  
  77.     {  
  78.         private List<StaticItem> StaticItemList;  
  79.   
  80.         public ProductTypeStaticListManager()  
  81.         {  
  82.             StaticItemList = new List<StaticItem>();  
  83.         }  
  84.   
  85.         public List<StaticItem> GetList()  
  86.         {  
  87.             StaticItemList.Add(new StaticItem { id = 1, Code = "0123", Description = "Watch" });  
  88.             StaticItemList.Add(new StaticItem { id = 2, Code = "0234", Description = "Shoes" });  
  89.             StaticItemList.Add(new StaticItem { id = 3, Code = "0345", Description = "" });  
  90.             return StaticItemList;  
  91.         }  
  92.     }  
  93.   
  94.     public class StaticItem  
  95.     {  
  96.         public int id { getset; }  
  97.         public string Code { getset; }  
  98.         public string Description { getset; }  
  99.     }  
  100. }  
Output

output

So the preceding code works the same as already described in the basic implementation of pattern. In the code another type of the list is fetched by passing a different key. For this implementation the keys are Country and Product. In a real application one can have more than this.

The preceding implementation follows the SOLID principle, just one exception is the Factory class that must be modifed when one wants to add a new key so it breaks the rule of single responsibility.

Note: Here the country and product list are hardcoded but in an actual program it is fetched from the database.

Conclusion

This pattern is very helpful in the scenario where one wants to create a pool of objects and share them among the clients (the clients are software programs or classes or web applications as in this example).

Note: This is my point of view regarding patterns. Please provide your feedback regarding it and also provide feedback if something you find is wrong in this.
 

Up Next
    Ebook Download
    View all
    Learn
    View all