【发布时间】:2015-12-14 02:25:09
【问题描述】:
我创建了一个抽象工厂类,其中包含一个将工厂创建的所有对象存储在数组中的方法。
abstract class ItemFactory{
function __construct($default_item){
$this->default_item = $default_item;
}
// Returns a new item + add the item to the factory items collection
function createFactoryItem(){
$this->addFactoryItem($object = clone $this->default_item);
return $object;
}
// Add the item to the collection of items created with the factory
function addFactoryItem($item_obj){
$this->items[] = $item_obj;
return $this;
}
}
ElementFactory 类扩展了 ItemFactory,SubElement 也是如此。
class ElementFactory extends ItemFactory{
function __construct(){
parent::__construct(new Element(new SubElement())));
}
}
我目前对下面示例中这种工厂模式的行为感到困惑。
$element_factory = new ElementFactory();
$element_factory->createFactoryItem()->setElementId(1);
$element_factory->createFactoryItem()->setElementId(2);
// Here I create a variable that stores the third element created from the factory
// setElementId() method belongs to Element and return $this
$element_3 = $element_factory->createFactoryItem()->setElementId(3);
// Here the part creating weird results
$element_3->getSubElementFactory()->createFactoryItem();
var_dump($element_factory);
我的预期是这样的:
ElementFactory Items:
Array
[0]: Element 1
[1]: Element 2
[2]: Element 3
'-- [0] : SubElement 1
Instead I get this:
[0]: Element 1
'-- [0] : SubElement 1
[1]: Element 2
'-- [0] : SubElement 1
[2]: Element 3
'-- [0] : SubElement 1
我创建了一个单独的变量来存储工厂创建的第三个对象,并且仅对第三个元素调用 getSubElementFactory()->createFactoryItem() 方法:为什么仍将 SubElement 对象添加到所有工厂元素在第三个而已?
非常感谢您的帮助
【问题讨论】: