• 组合模式


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

      比如文件系统,目录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
    ";
        }
        function scan(){
            echo "this is file $this->name 
    ";
            return;
        }
    }
    
    $zip = new ZipFile("zip");
    $zip->add(new File("xyz"));
    $zip->add(new File("abc"));
    echo '遍历$zip目录下的文件'."
    ";
    $zip->scan();
    /*
    遍历$zip目录下的文件
    this is file xyz 
    this is file abc 
    */
    
    echo "
    ";
    $dirA =  new Dir("dirA");
    $dirA->add(new File("php"));
    $dirA->add($zip);
    echo '遍历$dirA目录下的文件'."
    ";
    $dirA->scan();
    /*
    遍历$dirA目录下的文件
    this is file php 
    this is file xyz 
    this is file abc 
    */
    
    echo "
    ";
    $dirB = new Dir("dirB");
    $dirB->add(new File("Js"));
    $dirA->add($dirB);
    echo '遍历添加dirB之后的$dirA目录下的文件'."
    ";
    $dirA->scan();
    /*
    遍历添加dirB之后的$dirA目录下的文件
    this is file php 
    this is file xyz 
    this is file abc 
    this is file Js 
    */
    

      

  • 相关阅读:
    FastDFS--storage文件上传和下载问题
    Ubuntu18.04中安装virtualenv和virtualenvwrapper
    详解文件包含漏洞
    pikachu-数字型注入-sqlmap
    sqlmap命令手册
    SQL注入详解及技巧
    Linux中更新firefox
    DVWA-SQL注入
    CTF杂项题解题思路
    ubuntu搭建环境
  • 原文地址:https://www.cnblogs.com/-beyond/p/8735806.html
Copyright © 2020-2023  润新知