Skip to main content

Understanding the Flyweight Method Design Pattern in C#

 

The Flyweight Method design pattern is a structural pattern that helps reduce memory usage by sharing as much data as possible with other similar objects. It is particularly useful in scenarios where a large number of objects with similar properties are needed. The Flyweight Method  pattern achieves this by storing common data externally and referencing it, thereby minimizing memory consumption.

Understanding the Proxy Method Design Pattern in C#

Example Without the Flyweight Method Pattern

Let's consider a simple graphics application where we need to display a large number of circles with varying colors and coordinates. In a non-pattern approach, we might create a separate object for each circle, even if many circles share the same color.

using System;
using System.Collections.Generic;

namespace WithoutFlyweightMethodPattern
{
    // Circle class with color, x and y coordinates
    class Circle
    {
        public string Color { get; private set; }
        public int X { get; private set; }
        public int Y { get; private set; }

        public Circle(string color, int x, int y)
        {
            Color = color;
            X = x;
            Y = y;
        }

        public void Draw()
        {
            Console.WriteLine($"Drawing Circle [Color: {Color}, X: {X}, Y: {Y}]");
        }
    }

    // Client
    class Program
    {
        static void Main(string[] args)
        {
            List<Circle> circles = new List<Circle>();

            // Creating 1,000 circles with varying positions but only 5 colors
            string[] colors = { "Red", "Green", "Blue", "Yellow", "Black" };
            Random random = new Random();

            for (int i = 0; i < 1000; i++)
            {
                string color = colors[random.Next(colors.Length)];
                int x = random.Next(100);
                int y = random.Next(100);

                circles.Add(new Circle(color, x, y));
            }

            // Drawing all circles
            foreach (var circle in circles)
            {
                circle.Draw();
            }
        }
    }
}

Problems in the Non-Pattern Approach

  1. High Memory Usage: Creating a new object for each circle, even if many share the same color, results in a large amount of memory being used.
  2. Redundant Data: The same data (color) is stored multiple times, leading to redundancy and inefficiency.

How the Flyweight Method Pattern Solves These Problems

The Flyweight Method pattern minimizes memory usage by sharing common data (intrinsic state) among objects and storing unique data (extrinsic state) separately. In our example, the color is the intrinsic state, while the coordinates (x and y) are the extrinsic state.

Revisited Code with Flyweight Method Pattern

Let's implement the Flyweight Method pattern using a CircleFactory to manage shared instances of circles with the same color.

using System;
using System.Collections.Generic;

namespace FlyweightMethodPattern
{
    // Flyweight Interface
    interface ICircle
    {
        void Draw(int x, int y);
    }

    // Concrete Flyweight
    class Circle : ICircle
    {
        private string _color;

        public Circle(string color)
        {
            _color = color;
        }

        public void Draw(int x, int y)
        {
            Console.WriteLine($"Drawing Circle [Color: {_color}, X: {x}, Y: {y}]");
        }
    }

    // Flyweight Factory
    class CircleFactory
    {
        private static Dictionary<string, Circle> _circleMap = new Dictionary<string, Circle>();

        public static ICircle GetCircle(string color)
        {
            if (!_circleMap.ContainsKey(color))
            {
                _circleMap[color] = new Circle(color);
                Console.WriteLine($"Creating circle of color : {color}");
            }
            return _circleMap[color];
        }
    }

    // Client
    class Program
    {
        static void Main(string[] args)
        {
            // Creating 1,000 circles with varying positions but only 5 colors
            string[] colors = { "Red", "Green", "Blue", "Yellow", "Black" };
            Random random = new Random();

            for (int i = 0; i < 1000; i++)
            {
                string color = colors[random.Next(colors.Length)];
                int x = random.Next(100);
                int y = random.Next(100);

                ICircle circle = CircleFactory.GetCircle(color);
                circle.Draw(x, y);
            }
        }
    }
}

Benefits of the Flyweight Method Pattern

  1. Reduced Memory Usage: By sharing objects that have the same intrinsic state, the Flyweight Method pattern significantly reduces memory usage.
  2. Efficiency: The pattern avoids redundancy by storing shared data centrally.
  3. Scalability: It allows the creation of a large number of objects without a corresponding increase in memory usage.

Why Can't We Use Other Design Patterns Instead?

  • Singleton Pattern: The Singleton pattern ensures a single instance of a class, whereas the Flyweight Method pattern manages multiple instances with shared data.
  • Prototype Pattern: The Prototype pattern is about creating new objects by copying existing ones. It doesn't focus on sharing common data among objects.
  • Factory Method Pattern: While the Factory Method pattern is concerned with object creation, it doesn't inherently deal with sharing and minimizing memory usage like the Flyweight Method pattern.

Steps to Identify Use Cases for the Flyweight Method Pattern

  1. Large Number of Similar Objects: Identify situations where you need a large number of objects with similar properties.
  2. Memory Constraints: Use the Flyweight Method pattern when memory usage is a concern and you need to optimize resource usage.
  3. Shared Intrinsic State: Determine if there are common properties (intrinsic state) that can be shared among objects.
  4. Distinct Extrinsic State: Ensure that the unique properties (extrinsic state) can be managed separately from the shared state.

By applying the Flyweight Method design pattern, you can efficiently manage a large number of similar objects, reducing memory usage and improving system performance. This pattern is particularly valuable in scenarios where memory constraints are critical, such as in graphical applications or systems with limited resources.

Comments

Popular posts from this blog

Implementing and Integrating RabbitMQ in .NET Core Application: Shopping Cart and Order API

RabbitMQ is a robust message broker that enables communication between services in a decoupled, reliable manner. In this guide, we’ll implement RabbitMQ in a .NET Core application to connect two microservices: Shopping Cart API (Producer) and Order API (Consumer). 1. Prerequisites Install RabbitMQ locally or on a server. Default Management UI: http://localhost:15672 Default Credentials: guest/guest Install the RabbitMQ.Client package for .NET: dotnet add package RabbitMQ.Client 2. Architecture Overview Shopping Cart API (Producer): Sends a message when a user places an order. RabbitMQ : Acts as the broker to hold the message. Order API (Consumer): Receives the message and processes the order. 3. RabbitMQ Producer: Shopping Cart API Step 1: Install RabbitMQ.Client Ensure the RabbitMQ client library is installed: dotnet add package RabbitMQ.Client Step 2: Create the Producer Service Add a RabbitMQProducer class to send messages. RabbitMQProducer.cs : using RabbitMQ.Client; usin...

Clean Architecture: What It Is and How It Differs from Microservices

In the tech world, buzzwords like   Clean Architecture   and   Microservices   often dominate discussions about building scalable, maintainable applications. But what exactly is Clean Architecture? How does it compare to Microservices? And most importantly, is it more efficient? Let’s break it all down, from understanding the core principles of Clean Architecture to comparing it with Microservices. By the end of this blog, you’ll know when to use each and why Clean Architecture might just be the silent hero your projects need. What is Clean Architecture? Clean Architecture  is a design paradigm introduced by Robert C. Martin (Uncle Bob) in his book  Clean Architecture: A Craftsman’s Guide to Software Structure and Design . It’s an evolution of layered architecture, focusing on organizing code in a way that makes it  flexible ,  testable , and  easy to maintain . Core Principles of Clean Architecture Dependency Inversion : High-level modules s...

How Does My .NET Core Application Build Once and Run Everywhere?

One of the most powerful features of .NET Core is its cross-platform nature. Unlike the traditional .NET Framework, which was limited to Windows, .NET Core allows you to build your application once and run it on Windows , Linux , or macOS . This makes it an excellent choice for modern, scalable, and portable applications. In this blog, we’ll explore how .NET Core achieves this, the underlying architecture, and how you can leverage it to make your applications truly cross-platform. Key Features of .NET Core for Cross-Platform Development Platform Independence : .NET Core Runtime is available for multiple platforms (Windows, Linux, macOS). Applications can run seamlessly without platform-specific adjustments. Build Once, Run Anywhere : Compile your code once and deploy it on any OS with minimal effort. Self-Contained Deployment : .NET Core apps can include the runtime in the deployment package, making them independent of the host system's installed runtime. Standardized Libraries ...