实施工厂模式的正确方法是什么? [英] What is the right way to implement factory pattern?

查看:175
本文介绍了实施工厂模式的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道这是否是在PHP中创建对象和实现工厂模式的正确方法。我知道我们有工厂方法模式和抽象工厂模式,但是我们有一个如下所示的模式
http://noondreams.com/shared/data/pages/images/Factory.png

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
    }
 }
}


推荐答案

不,这不是一个真正的工厂模式。工厂模式看起来更像这样:

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.

注意:在一个真实情况下,你会不要使用switch语句,但可能是反射或其他各种技巧,因为抽象类不会知道它的所有子类。

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
{

}

这篇关于实施工厂模式的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆