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 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.

0.create project
Create new project

2. Lets create contract called “IShape” which will be implemented by different shapes.

1. IShape
IShape interface

3. Lets add “Rectangle” shape

2.rectangle
Rectangle class

4. Lets add “Circle” shape.

3.circle
Circle class

5. Lets add “Shapes” enum

6.shapes
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.

4.shapeobjectfactory
ShapeObjectFactory class

7. Client program

5. program
Program class

8. Execution of simple program

7.result
output

Advantage:

  1. We should use this design pattern when we need to create large number objects.
  2. 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!

Leave a Reply

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