PHP7 Flyweight

This commit is contained in:
Dominik Liebler
2016-09-23 10:34:53 +02:00
parent de196765cf
commit 2e287acdf7
7 changed files with 343 additions and 336 deletions

View File

@@ -4,33 +4,28 @@ namespace DesignPatterns\Structural\Flyweight\Tests;
use DesignPatterns\Structural\Flyweight\FlyweightFactory;
/**
* FlyweightTest demonstrates how a client would use the flyweight structure
* You don't have to change the code of your client.
*/
class FlyweightTest extends \PHPUnit_Framework_TestCase
{
private $characters = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', );
private $fonts = array('Arial', 'Times New Roman', 'Verdana', 'Helvetica');
// This is about the number of characters in a book of average length
private $numberOfCharacters = 300000;
private $characters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
private $fonts = ['Arial', 'Times New Roman', 'Verdana', 'Helvetica'];
public function testFlyweight()
{
$factory = new FlyweightFactory();
for ($i = 0; $i < $this->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);
foreach ($this->characters as $char) {
foreach ($this->fonts as $font) {
$flyweight = $factory->get($char);
$rendered = $flyweight->render($font);
$this->assertEquals(sprintf('Character %s with font %s', $char, $font), $rendered);
}
}
// Flyweight pattern ensures that instances are shared
// instead of having hundreds of thousands of individual objects
$this->assertLessThanOrEqual($factory->totalNumber(), count($this->characters));
// there must be one instance for every char that has been reused for displaying in different fonts
$this->assertCount(count($this->characters), $factory);
}
}