原型模式(Prototype Pattern)

百度词条的解释

http://baike.baidu.com/view/1781744.htm

<?php
//原型模式
//抽象要是原型
abstract class Key {

	private $name;
	private $owner;

	public function __construct($name, $owner) {
		$this->name = $name;
		$this->owner =$owner;
	}


	public function __set($key, $value) {
		$this->$key = $value;
	}

	public function __get($key) {
		if(isset($this->$key)) {
			return $this->$key;
		} else {
			return NULL;
		}
	}

	//克隆方法
	public abstract function cloneFun();

	public function toString() {
		return $this->name.',belongs to '.$this->owner;
	}

}

class GateKey extends Key {
	public function __construct($owner) {
		parent::__construct('Gate Key',$owner);
	}
	public function cloneFun() {
		return clone $this;
	}
}

class CabinetKey extends Key {
	public function __construct($owner) {
		parent::__construct('Gabine Key',$owner);
	}
	public function cloneFun() {
		return clone $this;
	}
}
////////////////////PHP完全可以直接 clone $oldGateKey 此模式是否还需要?
$oldGateKey = new GateKey('GF');
$newGateKey = $oldGateKey->cloneFun();
$newGateKey->owner = 'Me';
$oldCabineKey = new CabinetKey('Me');
$newCabinetKey = $oldCabineKey->cloneFun();
$newCabinetKey->owner = 'GF';

var_dump($oldGateKey);
var_dump($newGateKey);
var_dump($oldCabineKey);
var_dump($newCabinetKey);
?>

你可能感兴趣的:(原型模式(Prototype Pattern))