Flyweight Design Pattern

Introduction:
Flyweight design pattern target to minimizes the memory usage by sharing as much data as possible with other similar objects. It is very useful when have large amount of objects in memory which have lot of similar values. by sharing the similar values between all the objects, memory usage will be much less.
Example:
Suppose you want to create an application to manage Employees and form UI perspective you want to display Employees list as Icons and let user control how that icon looks like. But for all employees icons, you will have only one icon style.
All employees sharing the same icon’s attributes, thus there is no need to include the icon’s attributes inside the Employee class. By doing so, you will decrease memory utilization and accordingly make your application more efficient.
Below is a diagram that showing how we will use Flyweight design pattern

FlyweightDesignPattern

 

enum Shape { Square, Circle, Regtangle };
class IconAttributes
{
public IconAttributes()
{
ObjectCreationCounter++;
}
public static int ObjectCreationCounter{ get; set; }
public Color IconColor { get; set; }
public Size  IconSize { get; set; }
public Shape IconShape { get; set; }
public Image IconImage { get; set; }
public int TransparancyPercentage { get; set; }
}
class Employee
{
public IconAttributes IconAttributes { get; set; }
public string EmployeeFirstName { get; set; }
public string EmployeeLastName { get; set; }
public DateTime EmployeeDob { get; set; }
public override string ToString()
{
return “FirstName:  ” + EmployeeFirstName +
”          LastName:  ” + EmployeeLastName +Environment.NewLine +
”          Dob:       ” + EmployeeDob.ToString () + Environment.NewLine +
“Icone Coloe” + IconAttributes.IconColor.ToString() +
”          Icon Shape:  ” + IconAttributes.IconShape.ToString()+ Environment.NewLine +
“=====================================” + Environment.NewLine;
}
}
static void Main(string[] args)
{
IconAttributes iconAttribue = new IconAttributes();
iconAttribue.IconColor = Color.Red;
iconAttribue.IconShape = Shape.Regtangle;
iconAttribue.IconSize = new Size(10, 10);
iconAttribue.TransparancyPercentage = 100;
Employee e;
List<Employee> employees = new List<Employee>();
for (int i = 0; i < 5; i++)
{
e = new Employee();
e.EmployeeFirstName = “FirstName ” + i.ToString();
e.EmployeeLastName = “LastName ” + i.ToString();
e.EmployeeDob = new DateTime(1982, 3, 20);
e.IconAttributes = iconAttribue;
employees.Add(e);
}
foreach (Employee emp in employees)
{
Console.WriteLine(emp.ToString());
}
Console.WriteLine(“++++++++++++++++++++++++++++++++++++++++”);
Console.WriteLine(“ObjectCreationCounter for IconAttributes   : ” + IconAttributes.ObjectCreationCounter.ToString());
Console.ReadKey();
}

 

Download Code