@samara
The Flyweight design pattern is a structural pattern that is used to minimize memory usage by sharing as much data as possible with similar objects. In PHP, we can implement the Flyweight pattern using the following steps:
1 2 3 |
interface FlyweightInterface { public function operation(); } |
1 2 3 4 5 6 7 8 9 10 11 12 |
class ConcreteFlyweight implements FlyweightInterface { private $sharedData; public function __construct($sharedData) { $this->sharedData = $sharedData; } public function operation() { echo "Shared data: " . $this->sharedData . " "; } } |
1 2 3 4 5 6 7 8 9 10 11 |
class FlyweightFactory { private $flyweights = []; public function getFlyweight($sharedData) { if (!isset($this->flyweights[$sharedData])) { $this->flyweights[$sharedData] = new ConcreteFlyweight($sharedData); } return $this->flyweights[$sharedData]; } } |
1 2 3 4 5 6 7 8 9 10 |
$factory = new FlyweightFactory(); $flyweight1 = $factory->getFlyweight("data1"); $flyweight1->operation(); $flyweight2 = $factory->getFlyweight("data2"); $flyweight2->operation(); $flyweight3 = $factory->getFlyweight("data1"); $flyweight3->operation(); |
In the above code, when we create a new flyweight object with the same shared data, instead of creating a new object, we return the existing flyweight object from the pool. This way, we can optimize memory usage by sharing the common data between similar objects.
@samara
The Flyweight design pattern is a structural design pattern that aims to minimize memory usage by sharing common data between multiple objects. In PHP, you can implement the Flyweight pattern using the following steps:
1 2 3 |
interface Flyweight { public function operation($uniqueState); } |
1 2 3 4 5 6 7 8 9 10 11 |
class ConcreteFlyweight implements Flyweight { private $sharedState; public function __construct($sharedState) { $this->sharedState = $sharedState; } public function operation($uniqueState) { // Perform operations with sharedState and uniqueState } } |
1 2 3 4 5 6 7 8 9 10 |
class FlyweightFactory { private $flyweights = array(); public function getFlyweight($sharedState) { if (!isset($this->flyweights[$sharedState])) { $this->flyweights[$sharedState] = new ConcreteFlyweight($sharedState); } return $this->flyweights[$sharedState]; } } |
1 2 3 |
$factory = new FlyweightFactory(); $flyweight = $factory->getFlyweight("shared state"); $flyweight->operation("unique state"); |
By using the Flyweight pattern in PHP, you can reduce memory usage by sharing common data between multiple objects. This can be especially useful when dealing with large datasets or when creating many similar objects.