You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The flyweight pattern is used to reduce the memory usage by sharing the common data with other similar objects.
It is used when we need to create a large number of similar objects.
It is used to improve the performance of the application.
It is used to reduce the memory footprint of the application.
Structure
It consists of flyweight, flyweight factory, flyweight mapping and client (client does pattern execution).
Flyweight: An interface that will be implemented by the concrete flyweight class.
Flyweight Factory: A factory class that will create the flyweight objects.
Flyweight Mapping: A mapping class that will map the flyweight objects with the key.
Client: A client class that will use the flyweight objects.
Examples
// Object typeinternalenumShapeType{Circle,Square}// Flyweight classinterfaceIShape:IFlyweight<CoOrdinates>{}classCircle:IShape{publicvoidAction(CoOrdinatespoints){Console.Write("Drawing circle at co-ordinate => ");Console.WriteLine($"X1:{points.X1}, X2:{points.X2}, Y1:{points.Y1}, Y2:{points.Y2}");}}classSquare:IShape{publicvoidAction(CoOrdinatespoints){Console.Write("Drawing square at co-ordinate => ");Console.WriteLine($"X1:{points.X1}, X2:{points.X2}, Y1:{points.Y1}, Y2:{points.Y2}");}}// Object inputclassCoOrdinates{publicintX1{get;set;}publicintX2{get;set;}publicintY1{get;set;}publicintY2{get;set;}}// Client - Pattern executionIFlyweight<CoOrdinates>circle=newCircle();IFlyweight<CoOrdinates>square=newSquare();IFlyweightFactory<ShapeType,CoOrdinates>factory=newFlyweightFactory<ShapeType,CoOrdinates>(newFlyweightMapping<ShapeType,CoOrdinates>(ShapeType.Circle,circle),newFlyweightMapping<ShapeType,CoOrdinates>(ShapeType.Square,square));varcircleObj1=factory.GetObject(ShapeType.Circle);circleObj1.Action(newCoOrdinates{X1=1,X2=2,Y1=3,Y2=4});varsquareObj1=factory.GetObject(ShapeType.Square);squareObj1.Action(newCoOrdinates{X1=5,X2=6,Y1=7,Y2=8});varcircleObj2=factory.GetObject(ShapeType.Circle);circleObj2.Action(newCoOrdinates{X1=9,X2=10,Y1=11,Y2=12});varsquareObj2=factory.GetObject(ShapeType.Square);squareObj2.Action(newCoOrdinates{X1=5,X2=6,Y1=7,Y2=8});Console.WriteLine($"Is circleObj1 same as circleObj2? {circleObj1==circleObj2}");Console.WriteLine($"Is squareObj1 same as squareObj2? {squareObj1==squareObj2}");
// Output
Drawing circle at co-ordinate => X1:1, X2:2, Y1:3, Y2:4
Drawing square at co-ordinate => X1:5, X2:6, Y1:7, Y2:8
Drawing circle at co-ordinate => X1:9, X2:10, Y1:11, Y2:12
Drawing square at co-ordinate => X1:5, X2:6, Y1:7, Y2:8
Is circleObj1 same as circleObj2? True
Is squareObj1 same as squareObj2? True