Copy codeThe Code is as follows:
<? Php
/**
* Combination Mode
*
* The object is combined into a tree structure to represent the "part-whole" hierarchy, so that the customer's use of a single object and composite object is consistent.
*/
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 ();
}
}
// Instance
// Create a menu
$ SubMenu1 = new Menu ("sub menu1 ");
$ SubMenu2 = new Menu ("sub menu2 ");
$ SubMenu3 = new Menu ("sub menu3 ");
$ Item1 = new Item ("163", "www.163.com ");
$ Item2 = new Item ("sina", "www.sina.com ");
$ SubMenu1-> add ($ item1 );
$ SubMenu1-> add ($ item2 );
$ Item3 = new Item ("baidu", "www.baidu.com ");
$ Item4 = new Item ("google", "www.google.com ");
$ SubMenu2-> add ($ item3 );
$ SubMenu2-> add ($ item4 );
$ AllMenu = new Menu ("All Menu ");
$ AllMenu-> add ($ subMenu1 );
$ AllMenu-> add ($ subMenu2 );
$ AllMenu-> add ($ subMenu3 );
$ ObjClient = new Client ($ allMenu );
$ ObjClient-> displayMenu ();
$ ObjClient-> setMenu ($ subMenu2 );
$ ObjClient-> displayMenu ();