The Flyweight Design Pattern allows you to share instances of the same object across multiple calls.

In the example on this post I will be reusing a rectangle with the same color, that makes the color property “intrinsic”. But I will not share position and size across the instances, so those characteristics are “extrinsic”.

  1. namespace ConsoleApplication1
  2. {
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. var r = FlyweightFactory.Create("Red");
  8. var g = FlyweightFactory.Create("Green");
  9. var b = FlyweightFactory.Create("Blue");
  10. r.Draw(0, 0, 10, 10);
  11. r.Draw(0, 0, 20, 30);
  12. g.Draw(0, 0, 20, 30);
  13. FlyweightFactory.Create("Green").Draw(10, 20, 50, 70);
  14. b.Draw(0, 0, 20, 30);
  15. FlyweightFactory.Create("Purple").Draw(10, 20, 50, 70);
  16. Console.ReadKey(true);
  17. }
  18. }
  19. public class FlyweightFactory
  20. {
  21. private static ConcurrentDictionary<string, Rectangle> cache
  22. = new ConcurrentDictionary<string, Rectangle>();
  23. public static Rectangle Create(string key)
  24. {
  25. return cache.GetOrAdd(key, new Rectangle(key));
  26. }
  27. }
  28. public class Rectangle
  29. {
  30. public Guid ID { get; set; }
  31. public string ColorName { get; set; }
  32. public Rectangle(string name)
  33. {
  34. ID = Guid.NewGuid();
  35. ColorName = name;
  36. }
  37. public void Draw(int x, int y, int width, int height)
  38. {
  39. Console.WriteLine("Rectangle ({0}) instance: {1}"
  40. , ColorName, ID);
  41. Console.WriteLine("X: {0} Y: {1} W: {2} H: {3}"
  42. , x, y, width, height);
  43. Console.WriteLine();
  44. }
  45. }
  46. }

Output:

Flyweight

In a real world example: You could use it in game development. Imagine that you have a system to change a character’s clothes, you don’t need to create an instance of the character itself entirely, having to load expensive resources every time. You could just use a shared instance of the character’s model and have the clothes as the extrinsic part. (And hey, you could have another Flyweight system to reuse clothes instances as well).