1.1. Fabryka abstrakcyjna (Abstract Factory)

1.1.1. Przeznaczenie

Pozwala tworzyć powiązane lub zależne obiekty bez specyfikowania ich konkretnych klas. Tworzone obiekty zwykle implementują ten sam interfejs. Wzorzec Fabryki abstrakcyjnej kładzie nacisk na tworzenie obiektów konkretnej rodziny, a nie na sposób w jaki te obiekty są tworzone.

1.1.2. Diagram UML

Alt AbstractFactory UML Diagram

1.1.3. Kod

Ten kod znajdziesz również na 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
     */
    protected $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. Testy

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);
    }
}