为什么在写工厂 class 时使用 "getObject" 方法?
Why use "getObject" method when writing a Factory class?
通常 Factory
class 包含类似 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;
}
}
问题:为什么不直接通过构造函数return对象?
class Factory
{
function __construct($type)
{
if ($type) $object = new $type();
return $object;
}
}
因为你不能return除了你自己的构造函数实例之外的任何东西。构造函数的全部意义在于设置一个实例。工厂的全部意义在于从用户那里抽象出一些复杂的构造/设置逻辑。
工厂 class 通常有一个静态方法,如:
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
通常 Factory
class 包含类似 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;
}
}
问题:为什么不直接通过构造函数return对象?
class Factory
{
function __construct($type)
{
if ($type) $object = new $type();
return $object;
}
}
因为你不能return除了你自己的构造函数实例之外的任何东西。构造函数的全部意义在于设置一个实例。工厂的全部意义在于从用户那里抽象出一些复杂的构造/设置逻辑。
工厂 class 通常有一个静态方法,如:
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