问题
I just wonder if this is the right way to create objects and implement the factory pattern in PHP. I know we have factory method pattern and Abstract factory pattern, but do we have a pattern like the following http://noondreams.com/shared/data/pages/images/Factory.png ?
class Factory
{
public function make($format)
{
switch($format)
{
case Source::Assocs:
return new \Source\Formats\Assocs();
case Source::XML
return new \Source\Formats\XML();
//Some other formats
}
}
}
回答1:
No, this isn't really a factory pattern. The factory pattern would look more like this:
<?php
abstract class File
{
public static function createFromFile($filename)
{
$extension = /* get file extension */;
switch ($extension)
{
case 'xml':
return new XmlFile($filename);
break;
case 'php':
return new PhpFile($filename);
break;
}
throw new \InvalidArgumentException();
}
}
class XmlFile extends File
{
}
class PhpFile extends File
{
}
Notice how the abstract class is creating instances of concrete classes which extend it without the user having to worry about the various types it may return.
Note: in a real scenario, you wouldn't use a switch statement, but likely reflection or various other techniques since the abstract class wouldn't know all of it's child classes.
That may look more like this:
<?php
abstract class File
{
public static function createFromFile($filename)
{
$extension = /* get file extension */;
$extension = ucfirst($extension);
$reflection = new ReflectionClass($extension . 'File');
return $reflection->newInstanceArgs(array($filename));
}
}
class XmlFile extends File
{
}
class PhpFile extends File
{
}
来源:https://stackoverflow.com/questions/14781518/what-is-the-right-way-to-implement-factory-pattern