Flyweight Pattern

Problem: Designing objects down to the lowest levels of system "granularity" provides optimal flexibility, but can be unacceptably expensive in terms of performance and memory usage.

Purpose of Flyweight Pattern

  • Reduce storage costs for a large number of objects.
  • Share objects to be used in multiple contexts simultaneously.
  • Retain object oriented granularity and flexibility

What is the Flyweight Pattern

A flyweight is an object that minimizes memory by sharing data as much as possible with other similar objects.

The Flyweight pattern describes how to share objects to allow their use at fine granularities without prohibitive cost.

Each "flyweight" object is divided into two pieces: the state-dependent (extrinsic) part, and the state-independent (intrinsic) part. Intrinsic state is stored (shared) in the Flyweight object. Extrinsic state is stored or computed by client objects, and passed to the Flyweight when its operations are invoked.

Flyweight is appropriate for small, fine-grained classes like individual characters or icons on the screen.

Example:

Each character in a word document is represented as a single instance of a character class, but the positions where the characters are drawn on the screen are kept as external data. In this case, there only has to be one instance of each character, rather than one for each appearance of that character.

Flyweight uses in C#

If there are two instances of a String constant with identical characters, they could refer to the same storage location.

Implementing the Pattern

A school wants to print its student info (Student Name, Roll Number, School Name, School Address, Pin, and Country) where student name and roll numbers are different and all other things are the same for each student

Flyweight Pattern.cs

using System;
using System.Collections.Generic;
using System.Text;
 
namespace ConsoleDesignPattern
{
 
    class
Students  //Flyweight Class
    {
         public string schoolName =
"Delhi Public School";
         public string schoolAddress = "Mathura Road, Delhi";
         public string strPin = "01";
         public string strCountry = "India";
           
         void PrintStudentInfo(string studentName, string rollNumber)
         {
              Console.WriteLine(studentName + rollNumber + schoolName + schoolAddress + strPin + strCountry);

              Console.ReadLine();
         }
     }
}

Program.cs


class MainApp
{
     public static void Main()
     {
          // Implementing Flyweight Pattern (only one object is created for all students which will reduce memory usage)
          Students flyWeightClient = new Students();
          flyWeightClient.PrintStudentInfo("Nitin Mittal", "153551");
          flyWeightClient.PrintStudentInfo("Tom", "153550");
     }
}


Similar Articles