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 below example, we will use C# language to implement the example of it.
Type: Structural design pattern
Description: In early days of computing, memory was so much costly but today its getting cheaper day by day. Usually, in software application, memory needed to create and hold objects. Sometimes, some objects stay in memory for longer period of time. Its developer’s responsibility to remove object from memory whenever its further not needed to save memory. Another way to save memory is that use created object instead of create new object each time which will definitely save memory and improve performance of application.
To achieve this, we should have a pool of objects where we will keep all newly created objects. Whenever we need same object, we will query to pool and get that object. After query, if needed object doesn’t exist in pool, we will create new one and store it in pool. In higher language like c# or java, we can use Dictionary<Key,Value> or HashTable<Key,Value> to create pool.
Example:
1. Lets add new project. You can give any name you want to.
2. Lets create contract called “IShape” which will be implemented by different shapes.
3. Lets add “Rectangle” shape
4. Lets add “Circle” shape.
5. Lets add “Shapes” enum
6. Factory class which will hold all objects in dictionary (hashtable). If requested object not exist in this list, then it will create it else will return the already created one.
7. Client program
8. Execution of simple program
Advantage:
- We should use this design pattern when we need to create large number objects.
- Reduce 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!