Design patterns are proven solutions to software design problems. They help improve code quality, promote reusability, and increase maintainability. We use them to save time and produce quality, extensible and flexible code. In this article, we are going to introduce the Flyweight design pattern.
Flyweight pattern is a structural design pattern used to minimize memory usage and improve program performance. This pattern avoids excessive memory consumption by sharing objects with similar properties. Client codes uses shared objects instead of creating new ones throughout the program.
The Flyweight pattern consists of the following components:
Here is an example of the Flyweight pattern in C#:
// Flyweight interface
interface IShape
{
void Draw(int x, int y);
}
// Concrete Flyweight
class Circle : IShape
{
private int radius;
public Circle(int radius)
{
this.radius = radius;
}
public void Draw(int x, int y)
{
Console.WriteLine("Drawing circle with radius {0} at ({1}, {2})", radius, x, y);
}
}
// Flyweight Factory
class ShapeFactory
{
private Dictionary<int, IShape> shapes = new Dictionary<int, IShape>();
public IShape GetShape(int radius)
{
if (!shapes.ContainsKey(radius))
{
shapes.Add(radius, new Circle(radius));
}
return shapes[radius];
}
}
// Client
class Client
{
static void Main()
{
ShapeFactory factory = new ShapeFactory();
IShape circle1 = factory.GetShape(5);
circle1.Draw(1, 2);
IShape circle2 = factory.GetShape(10);
circle2.Draw(3, 4);
IShape circle3 = factory.GetShape(5);
circle3.Draw(5, 6);
}
}
In the example above, we have a Circle class that implements the IShape interface. The ShapeFactory class acts as a Flyweight Factory that creates and manages Circle objects based on radius. In the client code, we create three circles, two circles with different radius and one with the same radius as the first circle. By reusing the first circle, we reduce the number of objects that need to be created, which saves memory and improves performance.
The Flyweight pattern is useful in scenarios where you need to create many objects with similar properties. By using flyweights, you can minimize memory usage and improve application performance by reusing objects.
To read about other design patterns, you can use the list below. There is also a code repository on GitHub that includes all the design patterns.
I am Reza Babakhani, a software developer. Here I write my experiences, opinions and suggestions about technology. I hope that what I write is useful for you.
leave a comment