工厂的目的是什么?

时间:2013-10-07 06:15:54

标签: php kohana

我试图理解为什么要使用工厂而不是new运算符创建对象?例如:

$validatePost = Validation::factory($_POST);

而不是

$validatePost = new Validation($_POST);

类的静态方法factory完全相同:

public static function factory(array $array)
    {
        return new Validation($array);
    }

3 个答案:

答案 0 :(得分:3)

按照以下问题:

Constructors vs Factory Methods

时使用工厂方法模式
a class can't anticipate the class of objects it must create
a class wants its subclasses to specify the objects it creates
classes delegate responsibility to one of several helper subclasses, and you want to             
localize the knowledge of which helper subclass is the delegate

答案 1 :(得分:2)

这样您就可以使用一种方法创建所有对象。如果您需要添加其他功能来创建,例如,模型,您只需在应用程序文件夹中使用自己的方法覆盖原始的factory()方法。

答案 2 :(得分:1)

重要的是要注意Sunil答案中引用的原因(来自链接的讨论)是指“经典”的GoF工厂模式,它与此处的问题不一样

(例如,“类不能预期它必须创建的对象类”在这里不适用,其中一切都是静态确定的。)

静态工厂技术可用于不同目的,例如:通常用于各种风格的“finitons”(包括单身,其中n = 1),或封装集中(或其他非常重要)资源管理,或用于建筑灵活性理由丹尼斯在他的回答中提到;等

相关问题