Copy Code code as follows:
<?php
/**
* Combination Mode
*
* Combine objects into a tree structure to represent a "partial-whole" hierarchy that enables customers to have consistent use of individual objects and composite objects
*/
Abstract class MenuComponent
{
Public function Add ($component) {}
Public function Remove ($component) {}
Public Function GetName () {}
Public Function GetUrl () {}
Public Function display () {}
}
Class Menu extends MenuComponent
{
Private $_items = Array ();
Private $_name = null;
Public function __construct ($name)
{
$this->_name = $name;
}
Public function Add ($component)
{
$this->_items[] = $component;
}
Public function Remove ($component)
{
$key = Array_search ($component, $this->_items);
if ($key!== false) unset ($this->_items[$key]);
}
Public Function display ()
{
echo "--". $this->_name. "---------<br/>";
foreach ($this->_items as $item)
{
$item->display ();
}
}
}
Class Item extends MenuComponent
{
Private $_name = null;
Private $_url = null;
Public function __construct ($name, $url)
{
$this->_name = $name;
$this->_url = $url;
}
Public Function display ()
{
echo $this->_name. " # "$this->_url." <br/> ";
}
}
Class Client
{
Private $_menu = null;
Public function __construct ($menu)
{
$this->_menu = $menu;
}
Public Function SetMenu ($menu)
{
$this->_menu = $menu;
}
Public Function DisplayMenu ()
{
$this->_menu->display ();
}
}
Example
Create Menu
$subMenu 1 = new Menu ("Sub menu1");
$subMenu 2 = new Menu ("Sub menu2");
$subMenu 3 = new Menu ("Sub Menu3");
$item 1 = new Item ("163", "www.163.com");
$item 2 = new Item ("Sina", "www.sina.com");
$subMenu 1->add ($item 1);
$subMenu 1->add ($item 2);
$item 3 = new Item ("Baidu", "www.baidu.com");
$item 4 = new Item ("Google", "www.google.com");
$subMenu 2->add ($item 3);
$subMenu 2->add ($item 4);
$allMenu = new Menu ("all menu");
$allMenu->add ($subMenu 1);
$allMenu->add ($subMenu 2);
$allMenu->add ($subMenu 3);
$objClient = new Client ($allMenu);
$objClient->displaymenu ();
$objClient->setmenu ($subMenu 2);
$objClient->displaymenu ();