我想知道如果this tutorial在PHP中正确实现工厂设计模式。以下是实际的源代码。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"
根据一本书“设计模式”,由四人帮,工厂模式的适用性
- 一个类不能预见的类的对象,必须创建
- 一类希望其子类指定它创建的对象
- 类将责任委托给几个辅助子类之一,并且您想本地化哪些辅助子类是委托的知识
第一点,这个例子实际上知道要创建什么类的对象,即Automobile
,不是吗?
第二点,没有子类。 Automobile
类不会从AutomobileFactory
继承。我认为AutomobileFactory应该至少有一个由Automobile实现的功能,它处理对象创建。
有人可以澄清这一点吗?我刚开始学习设计模式,每次遇到与别人不同的教程时,都会让我困惑不已。
这几乎是相同的例子:) – 2013-05-13 14:33:49
我不同意 - 除了他们都生产汽车的事实。我们来看看你的清单,然后看Wiki的例子。 1.一个类无法预测它必须创建的对象类 - 对于CarFactory来说是真的 - 不知道它会产生什么。 2.一个类想要它的子类指定它创建的对象 - 真,检查出SedanFactory – 2013-05-13 14:37:34
但它知道它是'Sedan'。还有另一个例子(封装),这确实是不同的 – 2013-05-13 14:40:36