From d97f9831d5496e284965e7903365221b921aa605 Mon Sep 17 00:00:00 2001 From: janukobytsch Date: Mon, 2 Feb 2015 00:11:48 +0100 Subject: [PATCH] added flyweight pattern --- Structural/Flyweight/CharacterFlyweight.php | 36 +++++++++++++++++++ Structural/Flyweight/FlyweightFactory.php | 37 ++++++++++++++++++++ Structural/Flyweight/FlyweightInterface.php | 12 +++++++ Structural/Flyweight/Tests/FlyweightTest.php | 36 +++++++++++++++++++ 4 files changed, 121 insertions(+) create mode 100644 Structural/Flyweight/CharacterFlyweight.php create mode 100644 Structural/Flyweight/FlyweightFactory.php create mode 100644 Structural/Flyweight/FlyweightInterface.php create mode 100644 Structural/Flyweight/Tests/FlyweightTest.php 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)); + } +}