1.1. Abstract Factory

1.1.1. 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.

1.1.2. UML Diagram

Alt AbstractFactory UML Diagram

1.1.3. Code

You can also find these code on GitHub

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<?php

namespace DesignPatterns\Creational\AbstractFactory;

class JsonFactory extends AbstractFactory
{
    public function createText(string $content): Text
    {
        return new JsonText($content);
    }
}

HtmlFactory.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<?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

1
2
3
4
5
6
7
8
<?php

namespace DesignPatterns\Creational\AbstractFactory;

class JsonText extends Text
{
    // do something here
}

HtmlText.php

1
2
3
4
5
6
7
8
<?php

namespace DesignPatterns\Creational\AbstractFactory;

class HtmlText extends Text
{
    // do something here
}

1.1.4. 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
<?php

namespace DesignPatterns\Creational\AbstractFactory\Tests;

use DesignPatterns\Creational\AbstractFactory\HtmlFactory;
use DesignPatterns\Creational\AbstractFactory\JsonFactory;

class AbstractFactoryTest extends \PHPUnit_Framework_TestCase
{
    public function testCanCreateHtmlText()
    {
        $factory = new HtmlFactory();
        $text = $factory->createText('foobar');

        $this->assertInstanceOf('DesignPatterns\Creational\AbstractFactory\HtmlText', $text);
    }

    public function testCanCreateJsonText()
    {
        $factory = new JsonFactory();
        $text = $factory->createText('foobar');

        $this->assertInstanceOf('DesignPatterns\Creational\AbstractFactory\JsonText', $text);
    }
}