account_circle Toanph
date_range 15/06/2017
Abstract Factory
Purpose
To create series of related or dependent objects without specifying their concrete classes. Usually the created classes all implement the same interface. The client of the abstract factory does not care about how these objects are created, he just knows how they go together.
UML Diagram

Code
AbstractFactory.php
1
2
3
4
5
6
7
8
9
10
11
12 | <?php
namespace DesignPatterns\Creational\AbstractFactory;
/**
* In this case, the abstract factory is a contract for creating some components
* for the web. There are two ways of rendering text: HTML and JSON
*/
abstract class AbstractFactory
{
abstract public function createText(string $content): Text;
}
|
JsonFactory.php
| <?php
namespace DesignPatterns\Creational\AbstractFactory;
class JsonFactory extends AbstractFactory
{
public function createText(string $content): Text
{
return new JsonText($content);
}
}
|
HtmlFactory.php
| <?php
namespace DesignPatterns\Creational\AbstractFactory;
class HtmlFactory extends AbstractFactory
{
public function createText(string $content): Text
{
return new HtmlText($content);
}
}
|
Text.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 | <?php
namespace DesignPatterns\Creational\AbstractFactory;
abstract class Text
{
/**
* @var string
*/
private $text;
public function __construct(string $text)
{
$this->text = $text;
}
}
|
JsonText.php
| <?php
namespace DesignPatterns\Creational\AbstractFactory;
class JsonText extends Text
{
// do something here
}
|
HtmlText.php
| <?php
namespace DesignPatterns\Creational\AbstractFactory;
class HtmlText extends Text
{
// do something here
}
|
Test
Tests/AbstractFactoryTest.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 | <?php
namespace DesignPatterns\Creational\AbstractFactory\Tests;
use DesignPatterns\Creational\AbstractFactory\HtmlFactory;
use DesignPatterns\Creational\AbstractFactory\HtmlText;
use DesignPatterns\Creational\AbstractFactory\JsonFactory;
use DesignPatterns\Creational\AbstractFactory\JsonText;
use PHPUnit\Framework\TestCase;
class AbstractFactoryTest extends TestCase
{
public function testCanCreateHtmlText()
{
$factory = new HtmlFactory();
$text = $factory->createText('foobar');
$this->assertInstanceOf(HtmlText::class, $text);
}
public function testCanCreateJsonText()
{
$factory = new JsonFactory();
$text = $factory->createText('foobar');
$this->assertInstanceOf(JsonText::class, $text);
}
}
|