5
I’m creating a class using Factory Method and I came up with the following question:.
The use of static methods in Factories?
In many examples I found we have to create an instance of the class Factory, but in my case I haven’t thought of 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();
Note 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();