Php 不了解工厂模式是如何工作的
我创建了一个抽象工厂类,其中包含一个方法,该方法将工厂创建的所有对象存储在一个数组中Php 不了解工厂模式是如何工作的,php,oop,factory,Php,Oop,Factory,我创建了一个抽象工厂类,其中包含一个方法,该方法将工厂创建的所有对象存储在一个数组中 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
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也扩展了ItemFactory
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():为什么子元素对象仍然只添加到第三个工厂的所有元素中
非常感谢您的帮助我想这不是一个工厂,而是一个收藏 尽管如此,我认为你的问题不在于模式,而在于克隆 在PHP中,不是深度复制 根据为
ElementFactory
提供的示例,您可能正在将子元素
设置为元素类的成员变量
此克隆不遵循此链接并创建子元素的新副本。它将创建元素的新副本,但副本将复制到与原始元素相同的子元素的指针上
这意味着对其中一个调用getSubElementFactory
与对另一个调用相同。从而产生了三份拷贝的错觉
您可以做的是向类中添加一个\u clone
方法。此方法必须创建一个新的子元素
。(也要克隆吗?)
这将提供所需的行为。非常感谢这一伟大的见解,我在ElementFactory中添加了函数uuu clone(){$This->default\u item=clone$This->default\u item;return$This->default\u item;}
,但最终结果是一样的,我是否正确实现了深度复制,我在工厂中设置了克隆,而不是在工厂制作的item类中设置克隆。非常感谢您让我走上正轨。克隆方法是作者编写深度复制算法的基础。或者至少有助于标准化这些代码。