PHP設計模式之組合模式與案例分享

小云云
發布: 2023-03-21 08:56:01
原創
1346 人瀏覽過

組合模式能讓客戶以一致的方式處理個別物件以及組合物件。組合模式讓客戶端像修改設定檔一樣簡單的完成遞歸的動作,免除了客戶端的邏輯思考。將物件組合成樹狀結構以表示‘部分-整體’的層次結構。

PHP案例:

導航目錄的新增與刪除:

header("Content-type:text/html; charset=utf-8");
abstract class Component {
abstract function addNode(Component $obj);
abstract function removeNode(Component $obj);
abstract function show($str);
}
class Branch extends Component {
public $name='';
public $childNode = array();
public function __construct($name)
{
$this->name = $name;
}
public function addNode(Component $obj) {
// $this->childNode[] = $obj;
array_push($this->childNode,$obj);
}
public function removeNode(Component $obj) {
$key = array_search($obj, $this->childNode);
unset($this->childNode[$key]);
}
public function show($str="") {
echo $this->name."<br>";
$str.=" |- ";
foreach ($this->childNode as $val) {
echo $str;
$val->show($str);
}
}
}
class Leaf extends Component {
public $name;
public function __construct($name) {
$this->name = $name;
}
 function addNode(Component $obj) {
 return false;
 }
 function removeNode(Component $obj) {
 return false;
 }
 function show($str="") {
 echo $this->name."<br>";
 }
}
$branch1 = new Branch("家电类");
$leaf11 = new Leaf("电饭煲");
$leaf12 = new Leaf("电冰箱");
$leaf13 = new Leaf("洗衣机");
$branch1->addNode($leaf11);
$branch1->addNode($leaf12);
$branch1->addNode($leaf13);
$branch2 = new Branch("电脑类");
$branch21 = new Branch("台式机");
$branch22 = new Branch("笔记本");
$leaf221 = new Leaf("华硕");
$leaf222 = new Leaf("联想");
$leaf223 = new Leaf("华为");
$leaf224 = new Leaf("华夏");
$branch22->addNode($leaf221);
$branch22->addNode($leaf222);
$branch22->addNode($leaf223);
$branch22->addNode($leaf224);
$branch2->addNode($branch21);
$branch2->addNode($branch22);
$branch1->addNode($branch2);
$branch1->show();
登入後複製

相關推薦:

#相關推薦:

常見的PHP設計模式分享

php設計模式之服務定位器模式實例詳解

詳解PHP設計模式之建造者模式

php設計模式之觀察者模式詳解

php教學:php設計模式之前言

以上是PHP設計模式之組合模式與案例分享的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!