原型模式
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建对象。
一般在初始化的信息不发生变化的时候,克隆是最好的方法,隐藏的对象创建的细节,同时又能够提升性能。如果初始化类的时候时间比较长,New 多个类很占时间,使用原型模式可以节省开销。
原型模式实现:
class Prototype {
private $name = '';
private $age = 0;
private $sex = '';
private $experience = '';
//存储工作经历对象
private $ex = null;
public function __construct($name,$age,$sex)
{
$this->name = $name;
$this->age = $age;
$this->sex = $sex;
$this->ex = new Experience();
}
public function setExperience($time,$company)
{
// $this->experience = $experience;
$this->ex->_set('time',$time);
$this->ex->_set('company',$company);
}
public function showProfile()
{
echo 'Name:'.$this->name.'<br>';
echo 'Age:'.$this->age.'<br>';
echo 'Sex:'.$this->sex.'<br>';
echo 'Experience:'.$this->ex->_get('time').','.$this->ex->_get('company').'<br>';
}
}
class Experience{
private $time = '';
private $company = '';
public function _set($name,$value)
{
$this->$name = $value;
}
public function _get($name){
return $this->$name;
}
}
客户端代码:
$prototype = new Prototype('test','23','male');
$prototype->setExperience('2000','出生');
$prototype->showProfile();
$prototype1 = clone $prototype;
$prototype1->setExperience('2005','毕业');
$prototype1->showProfile();
结果:
Name:test
Age:23
Sex:male
Experience:2000,出生
Name:test
Age:23
Sex:male
Experience:2005,毕业