What is the right way to implement factory pattern?

风格不统一 提交于 2019-12-10 09:28:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!