8

This is its definition:

Use sharing to support large numbers of fine-grained objects efficiently.

But I can't figure out what it means exactly.

Can you elaborate with a tiny demo?

Gordon
  • 312,688
  • 75
  • 539
  • 559
user198729
  • 61,774
  • 108
  • 250
  • 348
  • 2
    I googled 'php flyweight pattern' and checked the first 3 results. Each yielded a comprehensive tutorial and extensive examples. – Mike B Feb 23 '10 at 04:20

1 Answers1

12

The Flyweight pattern is useful if you need a large number of instances of a particular type. You isolate the data that is the same for all these instances (the intrinsic state) into a shared object. You only keep the data that varies per instance in the instances themselves (the extrinsic state). The benefit is less memory consumption obviously.

It's a common pattern in the gaming industry where the usual example is Soldiers on the battle field. All Soldiers share the same graphical representation and the same weapons but their position and health is different. The extrinsic state would then only be their health and x/y/z coordinates on the battlefield while everything else would be in the Flyweight.

PHP Implementations for this pattern are easy to find on the web. For instance

Gordon
  • 312,688
  • 75
  • 539
  • 559