组合模式(Composite Pattern)--部分-整体模式

百度词条的解释

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

<?php
//组合模式
abstract class AbstractClass {

	private $name;

	private $list;

	public function add(AbstractClass $item) {
	}

	public function remove(AbstractClass $item) {
	}

}

//枝节点
class Limb extends AbstractClass {

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

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


	public function __construct() {
		$this->list = array();
	}

	public function add(AbstractClass $item) {
		array_push($this->list, $item);
	}

	public function remove(AbstractClass $item) {
		if($key = array_search($item, $this->list)) {
			unset($this->list[$key]);
		}
	}

	public function show() {
		echo $this->name.'<br/>';
		if(!empty($this->list)) {
			foreach($this->list AS $val) {
				echo '(Parent is'.$this->name.')';
				$val->show();
			}
		}
		return $this->name;
	}
}

//叶子节点
class Leaf extends AbstractClass {

	public function __construct() {
		$this->list = null;
	}

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

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

	public function show() {
		echo $this->name.',';
		return $this->name;
	}

}

class Tree {

	private $tree;

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

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

	public function getTree(AbstractClass $tree) {
		$tree->name = '1';
		$leaf2 = new Leaf();
		$leaf2->name = '2';
		$tree->add($leaf2);
		$limb3 = new Limb();
		$limb3->name = '3';
		$tree->add($limb3);
		$leaf4 = new Leaf();
		$leaf4->name = '4';
		$limb3->add($leaf4);
		$leaf5 = new Leaf();
		$leaf5->name = '5';
		$limb3->add($leaf5);
		$this->tree = $tree;
	}

}

$tree = new Tree();
$limb = new Limb();
$tree->getTree($limb);
echo $tree->tree->show();

?>

你可能感兴趣的:(function,tree,null,search,Class)