@
@
@Twitt2019-07-23 10:35:53
PHP
@Twitt, 2019-07-23 10:35:53

Is this code a factory method or a static factory?

There is a class that has a static method that receives an argument as input (in this example, transportId), there is a conditional operator that returns the desired transport based on the ID. It is important to note that the returned object in any case is the heir of one abstract class (in this case, AbstractTransport).

class TransportFactory
{
    public static function createTransport($transportId)
    {
        switch ($transportId) {
            case Transport::CARS:
                return new Car();
                break;
            case Transport::PLANE:
                return new Plane();
                break;
            case Transport::TRAIN:
                return new Train();
                break;
           default:
            throw new Exception("No active transport");
        }
    }
}

After reading about patterns, I don’t quite understand, is this a factory method, or a static simple factory? And who can explain?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikita Dergachov, 2019-07-23
@vanillathunder

This is a static factory.
https://refactoring.guru/en/design-patterns/factor...

D
Denis, 2019-07-23
@sidni

Think Factory Method
https://sourcemaking.com/design_patterns/factory_m... ( https://evileg.com/en/post/406/)
https://makedev.org/patterns/creational/factoryMet...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question