PHP OOP: Factory (faktorka) - továrna [8]

PHP OOP: Factory (faktorka) - továrna [8]

Návrhový vzor (creational pattern) Factory, alias faktorka či česky továrna (tovární metoda), se v objektově orientovaném programování (OOP) používá k vytváření objektů bez specifikace jejich tříd. Jinak řečeno díky factory získáme více abstrakce než při použití konstruktoru. Více ale jistě řeknou příklady, jdeme tedy na ně...

 

Factory

https://github.com/hydroxid/php_examples/blob/main/3663_factory/factory.php

class Product
{
    private string $name;

    public function __construct(string $name)
    {
        $this->name = $name;
    }

    public static function Book() : Product
    {
        return new Product('Book');
    }

    public static function Meal() : Product
    {
        return new Product('Meal');
    }
}

$book = Product::Book();
$meal = Product::Meal();

var_dump($book);
var_dump($meal);

 

Factory method

https://github.com/hydroxid/php_examples/blob/main/3663_factory/factory_method.php

class Product
{
    private string $name;

    public function __construct(string $name)
    {
        $this->name = $name;
    }
}

class FactoryProduct
{
    public function createBook() : Product
    {
        return new Product('Book');
    }

    public function createMeal() : Product
    {
        return new Product('Meal');
    }
}

$factory = new FactoryProduct();

$book = $factory->createBook();
$meal = $factory->createMeal();

var_dump($book);
var_dump($meal);

 

Factory method s interface

https://github.com/hydroxid/php_examples/blob/main/3663_factory/factory_method_interface.php

abstract class Factory
{
    abstract public function factoryMethod() : Item;

    public function init() : string
    {
        $item = $this->factoryMethod();
        var_dump($item);
        return $item->action();
    }
}

class BookFactory extends Factory
{
    public function factoryMethod() : Item
    {
        return new Book();
    }
}

class MealFactory extends Factory
{
    public function factoryMethod() : Item
    {
        return new Meal();
    }
}

interface Item
{
    public function action() : string;
}

class Book implements Item
{
    public function action() : string
    {
        return 'Book - done';
    }
}

class Meal implements Item
{
    public function action() : string
    {
        return 'Meal - done';
    }
}

function create(Factory $factory)
{
    return $factory->init();
}

$book = create(new BookFactory());
$meal = create(new MealFactory());

var_dump($book);
var_dump($meal);

Jak se ti článek líbil?

Komentáře (0)

Přidat komentář