Skip to content

Latest commit

 

History

History
50 lines (41 loc) · 921 Bytes

simple-factory.md

File metadata and controls

50 lines (41 loc) · 921 Bytes

Simple Factory Design Pattern

Simple factory simply creates an instance without exposing any instantiation details to the client.

How to apply

interface Book
{
    public function getName(): string;
}

class FantasyBook implements Book
{
    public function __construct(private string $name) {}

    public function getName(): string
    {
        return $this->name;
    }
}
class BookFactory
{
    public static function make($name): Book
    {
        return new FantasyBook($name);
    }
}

Usage:

$book = BookFactory::make("Lord of the Rings");
echo $book->getName();

Output:

Lord of the Rings

Note:

Example uses Constructor Property Promotion (PHP 8.0) syntax. Which declares and assigns class properties at the same time.

public function __construct(private string $name) {}

It's similar to Member initializer lists in C++.