I was reading up on factory methods. Can someone explain why it is suggested that factory methods be located in a separate factory class?
I am pulling my example from here: http://www.devshed.com/c/a/PHP/Design-Patterns-in-PHP-Factory-Method-and-Abstract-Factory/
class ETF {
var $data;
function __construct($data) {
$this->data = $data;
}
function process() {}
function getResult() {}
}
class VirtualCheck extends ETF {}
class WireTransfer extends ETF {}
class ETFFactory {
function createETF($data) {
switch ($data[‘etfType’]) {
case ETF_VIRTUALCHECK :
return new VirtualCheck($data);
case ETF_WIRETRANSFER :
return new WireTransfer($data);
default :
return new ETF($data);
}
}
}
$data = $_POST;
$etf = ETFFactory::createETF($data);
$etf->process();
I would tend to instead write it like this:
class ETF {
final public static function factory($data) {
switch ($data[‘etfType’]) {
case ETF_VIRTUALCHECK :
return new VirtualCheck($data);
case ETF_WIRETRANSFER :
return new WireTransfer($data);
default :
return new ETF($data);
}
}
var $data;
function ETF($data) {
$this->data = $data;
}
function process() {}
function getResult() {}
}
class VirtualCheck extends ETF {}
class WireTransfer extends ETF {}
$data = $_POST;
$etf = ETF::factory($data);
$etf->process();
Am I wrong in doing this?
ETFare factories. It is unnecessary behaviour (yet factory is for hiding implementations).