Introducing the Flyweight design pattern

Introducing the Flyweight design pattern

Read Time : 2 Minutes

Sunday, 30 April 2023

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:

  • Flyweight: The interface that flyweights or shared objects must implement.
  • Concrete Flyweight: This class implements the Flyweight interface. Objects of this class will be shared objects.
  • Flyweight Factory: Creates and manages shared objects and ensures that objects are shared correctly.
flyweight pattern

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.

design patterns

Creational:Factory Design Pattern
Builder Design Pattern
Singleton Design Pattern
Prototype Design Pattern
Abstract Factory Design Pattern
Structural:Adapter Design Pattern
Bridge Design Pattern
Composite Design Pattern
Decorator Design Pattern
Facade Design Pattern
Flyweight Design Pattern
Proxy Design Pattern
Behavioral:Chain of Responsibility Design Pattern
Command Design Pattern
Interpreter Design Pattern
Mediator Design Pattern
Memento Design Pattern
Observer Design Pattern
State Design Pattern
Strategy Design Pattern
Template Method Design Pattern
Visitor Design Pattern
Iterator Design Pattern
  • Share:
reza babakhani
Reza Babakhani

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.

Latest post

Service Mesh Simplifying Microservice Communication

In the ever-evolving landscape of software development, microservices architecture has gained considerable popularity due to its scalability, flexibility, and extensibility. However, as the number of microservices in an application increases, it becomes increasingly challenging to manage their communication and ensure that they are all properly visible. This is where Service Mesh comes into play.

The Importance of Edge Computing

Due to the speed of technological evolution, one of the concepts that has attracted a lot of attention and changes the way we interact with digital systems is edge computing.

What is event-driven architecture?

Event-driven architecture (EDA) is a software design pattern that has become increasingly popular in modern software development. In this architecture, the flow of data is determined by the occurrence of events. Unlike traditional centralized systems that are constantly checking for new status. Event-driven architecture is especially useful for systems that need to process large amounts of data in real-time.

leave a comment