组合模式

  组合模式,我的理解就是:一个对象内部可以包含很多种类型的对象,并且被包含的这些对象同样有这个属性,都拥有相同的操作。

  比如文件系统,目录A下面有B目录和C目录,B目录下有D目录和E目录。     

  可以对A目录进行重命名、删除、移动和复制等操作,与此同时可以对B、C、D、E目录进行同样的操作,并且在移动目录的时候,可以将B目录下D目录移动到A目录下,结果就是与B同级。  

<?php
abstract class FileSystem{
    abstract function add(FileSystem $fs);
    abstract function scan(); 
}

class Dir extends FileSystem{
    public  $fs = array();
    public $name;
    public function __construct($name){
        $this->name = $name;
    }
    function add(FileSystem $fs){
        if( in_array($fs, $this->fs, true) ){
            return;
        }
        $this->fs[] = $fs;
    }
    function scan(){
        foreach($this->fs as $dir){
            $dir->scan();
        }
    }
}

class ZipFile extends FileSystem{
    public  $fs = array();
    public $name;
    public function __construct($name){
        $this->name = $name;
    }
    function add(FileSystem $fs){
        if( in_array($fs, $this->fs, true) ){
            return;
        }
        $this->fs[] = $fs;
    }
    function scan(){
        foreach($this->fs as $dir){
            $dir->scan();
        }
    }
}

class File extends FileSystem{
    public $name;
    public function __construct($name){
        $this->name = $name;
    }
    function add(FileSystem $fs){
        echo "this is file ,can't add some file or dir to this file\n";
    }
    function scan(){
        echo "this is file $this->name \n";
        return;
    }
}

$zip = new ZipFile("zip");
$zip->add(new File("xyz"));
$zip->add(new File("abc"));
echo '遍历$zip目录下的文件'."\n";
$zip->scan();
/*
遍历$zip目录下的文件
this is file xyz 
this is file abc 
*/

echo "\n";
$dirA =  new Dir("dirA");
$dirA->add(new File("php"));
$dirA->add($zip);
echo '遍历$dirA目录下的文件'."\n";
$dirA->scan();
/*
遍历$dirA目录下的文件
this is file php 
this is file xyz 
this is file abc 
*/

echo "\n";
$dirB = new Dir("dirB");
$dirB->add(new File("Js"));
$dirA->add($dirB);
echo '遍历添加dirB之后的$dirA目录下的文件'."\n";
$dirA->scan();
/*
遍历添加dirB之后的$dirA目录下的文件
this is file php 
this is file xyz 
this is file abc 
this is file Js 
*/

  

posted @ 2018-04-07 23:56  寻觅beyond  阅读(179)  评论(0编辑  收藏  举报
返回顶部