簡介:
組合模式,屬于結構型的設計模式,將物件組合成樹形結構以表示“部分-整體”的層次結構,組合模式使得用戶對單個物件和組合物件的使用具有一致性,
組合模式分兩種狀態:
- 透明方式,子類的所有介面一致,使其葉子節點和枝節點對外界沒有區別,
- 安全方式,子類介面不一致,只實作特定的介面,
適用場景:
希望客戶端可以忽略組合物件與單個物件的差異,進行無感知的呼叫,
優點:
讓客戶端忽略層次之間的差異,方便對每個層次的資料進行處理,
缺點:
如果服務端限制型別時,資料不方便處理,
代碼:
// component為組合中的物件介面,在適當的情況下,實作所有類共有介面的默認行為,宣告一個介面用于訪問和管理Component的字部件,
abstract class Component {
protected $name;
function __construct($name) {
$this->name = $name;
}
//通常用add和remove方法來提供增加或移除樹枝或樹葉的功能
abstract public function add(Component $c);
abstract public function remove(Component $c);
abstract public function display($depth);
}
//透明方式和安全方式的區別就在葉子節點上,透明方式的葉子結點可以無限擴充,然而安全方式就是對其做了絕育限制,
class Leaf extends Component {
public function add(Component $c) {
echo "不能在添加葉子節點了\n";
}
public function remove(Component $c) {
echo "不能移除葉子節點了\n";
}
// 葉節點的具體方法,此處是顯示其名稱和級別
public function display($depth) {
echo '|' . str_repeat('-', $depth) . $this->name . "\n";
}
}
//composite用來處理子節點,控制添加,洗掉和展示(這里的展示可以是任意功能)
class Composite extends Component
{
//一個子物件集合用來存盤其下屬的枝節點和葉節點,
private $children = [];
public function add(Component $c) {
array_push($this->children, $c);
}
public function remove(Component $c) {
foreach ($this->children as $key => $value) {
if ($c === $value) {
unset($this->children[$key]);
}
}
}
public function display($depth) {
echo str_repeat('-', $depth) . $this->name . "\n";
foreach ($this->children as $component) {
$component->display($depth);
}
}
}
//客戶端代碼
//宣告根節點
$root = new Composite('根');
//在根節點下,添加葉子節點
$root->add(new Leaf("葉子節點1"));
$root->add(new Leaf("葉子節點2"));
//宣告樹枝
$comp = new Composite("樹枝");
$comp->add(new Leaf("樹枝A"));
$comp->add(new Leaf("樹枝B"));
$root->add($comp);
$root->add(new Leaf("葉子節點3"));
//添加并洗掉葉子節點4
$leaf = new Leaf("葉子節點4");
$root->add($leaf);
$root->remove($leaf);
//展示
$root->display(1);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/542383.html
標籤:其他
上一篇:day09-AOP-02
下一篇:模塊
