zoukankan      html  css  js  c++  java
  • 组合模式

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

      比如文件系统,目录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 
    */
    

      

  • 相关阅读:
    6大集合类
    数据导出到Excel/Word 防止出现乱码仅有一行数据导出的时候
    bootmgr is compressed 解决办法 汇总
    RAID 独立磁盘真阵列
    C# 和 Js 取出时间间隔
    Image 获取缩略图
    ConvertJSONDateToJSDateObject 方法实现json格式时间串转换为 对应的时间格式串
    纯js脚本的模式对话框
    癌症的IARC分级
    微信小程序如何在页面间传值
  • 原文地址:https://www.cnblogs.com/-beyond/p/8735806.html
Copyright © 2011-2022 走看看