diff --git a/Structural/Flyweight/CharacterFlyweight.php b/Structural/Flyweight/CharacterFlyweight.php new file mode 100644 index 0000000..77d6b2d --- /dev/null +++ b/Structural/Flyweight/CharacterFlyweight.php @@ -0,0 +1,36 @@ +name = $name; + } + + /** + * Clients supply the context-dependent information that the flyweight needs to draw itself + * For flyweights representing characters, extrinsic state usually contains e.g. the font + * @param string $font + */ + public function draw($font) + { + print_r("Character {$this->name} printed $font \n"); + } + +} \ No newline at end of file diff --git a/Structural/Flyweight/FlyweightFactory.php b/Structural/Flyweight/FlyweightFactory.php new file mode 100644 index 0000000..4558300 --- /dev/null +++ b/Structural/Flyweight/FlyweightFactory.php @@ -0,0 +1,37 @@ +pool)) { + $this->pool[(string) $name] = new CharacterFlyweight((string) $name); + } + return $this->pool[(string) $name]; + } + + public function totalNumber() + { + return sizeof($this->pool); + } + +} \ No newline at end of file diff --git a/Structural/Flyweight/FlyweightInterface.php b/Structural/Flyweight/FlyweightInterface.php new file mode 100644 index 0000000..cf43d57 --- /dev/null +++ b/Structural/Flyweight/FlyweightInterface.php @@ -0,0 +1,12 @@ +numberOfCharacters; $i++) { + $char = $this->characters[array_rand($this->characters)]; + $font = $this->fonts[array_rand($this->fonts)]; + $flyweight = $factory->$char; + // External state can be passed in like this: + // $flyweight->draw($font); + } + + // Flyweight pattern ensures that instances are shared + // instead of having hundreds of thousands of individual objects + $this->assertLessThanOrEqual($factory->totalNumber(), sizeof($this->characters)); + } +}