I'm creating a simple class using Factory Method and the following question came up for me.
Is it good practice to use static methods in Factories?
In many examples I found there, we have an instance of the Factory class, and I have not identified any reason why it needs to be instantiated.
<?php
/* Factory and car interfaces */
interface CarFactory {
public function makeCar();
}
interface Car {
public function getType();
}
/* Implementações da Factory e Car */
class SedanFactory implements CarFactory {
public function makeCar() {
return new Sedan();
}
}
class Sedan implements Car {
public function getType() {
return 'Sedan';
}
}
/* Client */
$factory = new SedanFactory();
$car = $factory->makeCar();
print $car->getType();
Notice the difference in implementation with static methods:
<?php
/* Factory and car interfaces */
interface CarFactory {
public static function makeCar();
}
interface Car {
public function getType();
}
/* Implementações da Factory e Carro */
class SedanFactory implements CarFactory {
public static function makeCar() {
return new Sedan();
}
}
class Sedan implements Car {
public function getType() {
return 'Sedan';
}
}
/* Client */
$car = SedanFactory::makeCar();
print $car->getType();