码迷,mamicode.com
首页 > 其他好文 > 详细

组合模式

时间:2015-01-17 13:52:21      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

组合模式:将对象组合成树形结构以表示“部分-整体”的层次结构。Composite使得用户对单个对象和组合对象的使用具有一致性。引用场景如树形结构,父子的操作具有一致性。

类图如下:

技术分享

典型的组合模式对象结构图:

技术分享

php实现:

<?php
abstract class Component{
    function __construct($strName){
        $this->m_strName = $strName;
    }
    abstract function Add($com);
    protected function Remove($com){}
    abstract function Display($nDepth);

}

class Leaf extends Component{
    function Add($com){
        print_r("Leaf can‘t add!");
    }
    function Display($nDepth){
        $strtemp = "";
        for($i=0;$i<$nDepth;$i++){
            $strtemp.="-";
        }
        $strtemp=$strtemp.($this->m_strName)."\n";
        print_r($strtemp);
    }
}

class Composite extends Component{
    protected $m_strName="";
    protected $c=array();
    function __construct($strName){
        $this->m_strName = $strName;
    }
    function Add($com){
        $this->c[] = $com;
    }
    function Remove($com){
        $key = array_search($com, $this->c);
        if($key != false)unset($this->c[$key]);
    }
    function Display($nDepth){
        $strtemp = "";
        for($i=0;$i<$nDepth;$i++){
            $strtemp.="-";
        }
        $strtemp=$strtemp.($this->m_strName)."\n";
        print_r($strtemp);
        foreach($this->c as $v){
            $v->Display($nDepth+2);
        }
    }
}

$p = new Composite("第一级目录");
$p->Add(new Leaf("第二级目录1"));
$s1 = new Leaf("第二级目录2");
$p->Add($s1);
$s2 = new Composite("第二级目录3");
$s2->Add(new Leaf("第三级目录1"));
$t1 = new Composite("第三级目录2");
$t1->Add(new Leaf("第四级目录"));
$s2->Add($t1);
$p->Add($s2);
$p->Remove($s1);
$p->Display(1);

  执行结果如下:

  -第一级目录
  ---第二级目录1
  ---第二级目录3
  -----第三级目录1
  -----第三级目录2
  -------第四级目录

组合模式

标签:

原文地址:http://www.cnblogs.com/zhutianpeng/p/4230263.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!