Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement flyweight pattern in php?

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?

like image 744
user198729 Avatar asked Feb 23 '10 04:02

user198729


People also ask

In which scenario you will prefer the flyweight design pattern most?

Flyweight pattern is used when we need to create a large number of similar objects (say 105). One important feature of flyweight objects is that they are immutable. This means that they cannot be modified once they have been constructed.

What type of design pattern is flyweight?

Flyweight is a structural design pattern that lets you fit more objects into the available amount of RAM by sharing common parts of state between multiple objects instead of keeping all of the data in each object.

What is the meaning of Flyweight pattern?

In computer programming, the flyweight software design pattern refers to an object that minimizes memory usage by sharing some of its data with other similar objects. The flyweight pattern is one of twenty-three well-known GoF design patterns.


1 Answers

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

  • http://sourcemaking.com/design_patterns/flyweight for a general description and
  • http://sourcemaking.com/design_patterns/flyweight/php for a concrete example in PHP.
like image 165
Gordon Avatar answered Oct 02 '22 22:10

Gordon