How to implement flyweight pattern in php?
Asked Answered
C

1

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?

Corbel answered 23/2, 2010 at 4:8 Comment(1)
I googled 'php flyweight pattern' and checked the first 3 results. Each yielded a comprehensive tutorial and extensive examples.Ignazio
Q
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

Qualify answered 23/2, 2010 at 7:51 Comment(4)
well, as always Gordon, great example +1Hinduism
In book shelf example where is the intrinsic property in Flyweight?Tinsmith
@KirenSiva author and titleQualify
@Qualify Ok thank you. May I please know about extrinsic properties in the example?Tinsmith

© 2022 - 2024 — McMap. All rights reserved.