2013-05-28 50 views
0

我目前的设计模式,并在书中读一本书,他用这样一个例子:分配多个类初始化的对象

<?php 
//Client.php 
/*Age groups: 
18-29: Group 1 
30-39: Group 2 
40-49: Group 3 
50+ : Group 4 
*/ 
function __autoload($class_name) 
{ 
    include $class_name . '.php'; 
} 

class Client 
{ 
    //$hotDate is component instance 
    private $hotDate; 

    public function __construct() 
    { 
     $this->hotDate=new Female(); 
     $this->hotDate->setAge("Age Group 4"); 
     echo $this->hotDate->getAge(); 
     $this->hotDate=$this->wrapComponent($this->hotDate); 
     echo $this->hotDate->getFeature(); 
    } 

    private function wrapComponent(IComponent $component) 
    { 
     $component=new ProgramLang($component); 
     $component->setFeature("php"); 
     $component=new Hardware($component); 
     $component->setFeature("lin"); 
     $component=new Food($component); 
     $component->setFeature("veg"); 
     return $component; 
    } 
} 

$worker=new Client(); 
?> 

我的问题是wrapComponent功能。如何在不丢失以前的内容的情况下多次初始化类变量?在我看来,这将返回唯一的事情是与食品类成分,因为它是最后一个被初始化。对不起,如果这是明显的问题,但我无法在网上找到任何东西,我从来没有见过这样做过。

+0

方法'ProgramLang','Hardware'和'Food'可能与以前的数据+新数据中返回一个对象。所以结果可以是累积的。 – kevinamadeus

回答

0

要记住的是对象是通过引用传递,因此,当您重新分配值参考它只能破坏对象的事情是有它没有其他的引用。

新操作解决了每种情况下的分配,以便参考被保持在整个链中的部件,在每个新创建的对象的存在,所述参考之前。

0

这可能是修饰模式的实现。
查找here的其他为例,可以帮助你了解这种模式。