通常,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;
}
}
答案 0 :(得分:2)
因为你不能从构造函数中返回除你自己的实例之外的任何东西。构造函数的重点是设置一个实例。工厂的重点是从用户那里抽象出一些复杂的构造/设置逻辑。
工厂类通常有一个静态方法,如:
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