PHP 设计模式之-组合模式

  上一文章为大家讲解了PHP观察者模式,这里再为大家分享一个组合模式,组合模式有时候又叫做部分-整体模式,它把程序内部简单元素和复杂元素提供给客户端统一的接口,使客户端和程序的内部结构结构,内部可以随意更改扩展。

  从类图上看组合模式形成一种树形结构,由枝干和叶子继承Compont显然不符合里氏代换原则。

  组合模式类图:

  <?php

      abstract class MenuComponent

  {

  public $name;

  public abstract function getName();

  public abstract function add(MenuComponent $menu);

  public abstract function remove(MenuComponent $menu);

  public abstract function getChild($i);

  public abstract function show();

  }

  class MenuItem extends MenuComponent

  {

  public function __construct($name)

  {

  $this->name = $name;

  }

  public function getName(){

  return $this->name;

  }

  public function add(MenuComponent $menu){

  return false;

  }

  public function remove(MenuComponent $menu){

  return false;

  }

  public function getChild($i){

  return null;

  }

  public function show(){

  echo " |-".$this->getName()."\n";

  }

  }

  class Menu extends MenuComponent

  {

  public $menuComponents = array();

  public function __construct($name)

  {

  $this->name = $name;

  }

  public function getName()

  {

  return $this->name;

  }

  public function add(MenuComponent $menu)

  {

  $this->menuComponents[] = $menu;

  }

  public function remove(MenuComponent $menu)

  {

  $key = array_search($menu, $this->menuComponents);

  if($key !== false) unset($this->menuComponents[$key]);

  }

  public function getChild($i)

  {

  if(isset($this->menuComponents[$i])) return $this->menuComponents[$i];

  return null;

  }

  public function show()

  {

  echo ":" . $this->getName() . "\n";

  foreach($this->menuComponents as $v){

  $v->show();

  }

  }

  }

  class testDriver

  {

  public function run()

  {

  $menu1 = new Menu('文学');

  $menuitem1 = new MenuItem('绘画');

  $menuitem2 = new MenuItem('书法');

  $menuitem3 = new MenuItem('小说');

  $menuitem4 = new MenuItem('雕刻');

  $menu1->add($menuitem1);

  $menu1->add($menuitem2);

  $menu1->add($menuitem3);

  $menu1->add($menuitem4);

  $menu1->show();

  }

  }

  $test = new testDriver();

  $test->run();本站内容如转载,需注明来源:银众网络,本文链接:http://www.yinzhong.net/article/142.html