为什么在编写工厂类时使用"getObject"方法?



通常,Factory类包含类似getObject的方法。

从而

class Factory
{
    private $type;
    function __construct($type)
    {
        $this->type = $type;
    }
    function getObject()
    {
        //example for brevity only to show use of $type variable
        if ($this->type) $object = new $type();
        return $object;
    }
}

问题:为什么不通过构造函数直接返回对象?

class Factory
{
    function __construct($type)
    {
        if ($type) $object = new $type();
        return $object;
    }
}

因为除了构造函数中您自己的实例之外,您不能返回任何内容。构造函数的全部意义在于设置一个实例。工厂的全部意义在于从用户那里抽象出一些复杂的构造/设置逻辑。

工厂类通常具有静态方法,如下所示:

class Foo {
    public function __construct($x, $y) {
        // do something
    }
    // this is a factory method
    public static function createFromPoint(Point $point) {
        return new self($point->x, $point->y);
    }
}
$foo = Foo::createFromPoint(new Point(1, 1)); // makes no sense but shows the concept