R
R
Romi2021-08-04 17:10:01
PHP
Romi, 2021-08-04 17:10:01

What is the advantage of a "factory method" over just creating objects?

The wiki gives this example:

<?php
abstract class Animal
{
    public static function initial($animal)
    {
        return new $animal();
    }
    abstract public function voice();
}

class Lion extends Animal
{
    public function voice()
    {
        echo 'Rrrrrrrr i\'m the lion <br />' . PHP_EOL;
    }
}

class Cat extends Animal
{
    public function voice()
    {
        echo 'Meow, meow i\'m the kitty <br />' . PHP_EOL;
    }
}

$animal1 = Animal::initial('Lion');
$animal2 = Animal::initial('Cat');

$animal1->voice();
$animal2->voice();


but I don't understand why this is better than the simple: what's the point? Thank you.

(new Cat())->voice();


Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lander, 2021-08-04
@romicohen

Just a stupid example. Imagine that you need to create different animals depending on the time of day. Lions at night, kittens by day. And not in one place of the application. Then the initial method will include a check for the time of day and, depending on this, give the desired animal. And this will automatically happen wherever Animal::initial() is called.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question