我想知道本教程是否在 PHP 中正确实现了工厂设计模式。下面是实际的源代码。
<?php
class Automobile
{
private $vehicle_make;
private $vehicle_model;
public function __construct($make, $model)
{
$this->vehicle_make = $make;
$this->vehicle_model = $model;
}
public function get_make_and_model()
{
return $this->vehicle_make . ' ' . $this->vehicle_model;
}
}
class AutomobileFactory
{
public static function create($make, $model)
{
return new Automobile($make, $model);
}
}
// have the factory create the Automobile object
$veyron = AutomobileFactory::create('Bugatti', 'Veyron');
print_r($veyron->get_make_and_model()); // outputs "Bugatti Veyron"
根据Gang of Four的《设计模式》一书,工厂模式的适用性是
- 一个类不能预测它必须创建的对象类
- 一个类希望它的子类指定它创建的对象
- 类将责任委托给几个助手子类之一,并且您希望本地化哪个助手子类是委托的知识
第一点,这个例子实际上知道要创建什么类的对象,Automobile
不是吗?
第二点,没有子类。Automobile
类不继承自AutomobileFactory
. 我认为汽车工厂应该至少有一个由汽车实现的功能,它处理对象的创建。
有人可以澄清一下吗?刚开始学习设计模式,每次遇到和别人不一样的教程,都让我很困惑。