• 【php设计模式】组合模式


      定义:

      是用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象,用来表示部分以及整体层次。这种类型的设计模式属于结构型模式,它创建了对象组的树形结构。

      应用场景:

      部分、整体场景,如树形菜单,文件、文件夹的管理

      通俗解释:

      组合模式,就是在一个对象中包含其他对象,这些被包含的对象可能是终点对象(不再包含别的对象),也有可能是非终点对象(其内部还包含其他对象,或叫组对象),我们将对象称为节点,即一个根节点包含许多子节点,这些子节点有的不再包含子节点,而有的仍然包含子节点,以此类推。很明显,这是树形结构,终结点叫叶子节点,非终节点(组节点)叫树枝节点,第一个节点叫根节点。同时也类似于文件目录的结构形式:文件可称之为终节点,目录可称之为非终节点(组节点)。

    实现如图所示的树形结构

    interface Node{
        public function add(Node $node);
    }
    
    class Branch implements Node{
        static $i = 0;
        public $name;
        public $node_list;
        public function __construct($name){
            $this->name = $name;
        } 
    
        public function add(Node $node){
            $this->node_list[] = $node;
        }
    
    }
    
    class Leaf implements Node{
        public $name;
        public function __construct($name){
            $this->name = $name;
        }
    
        public function add(Node $node){
            throw new Exception("Leaf don't add sub nodes");
        }
    }
    
    $branch = new Branch("主干");
    
    $branch_left = new Branch("左树枝");
    $branch_right = new Branch("右树枝");
    
    
    $leaf1 = new Leaf("左第一片树叶");
    $leaf2 = new Leaf("左第二片树叶");
    
    $branch->add($branch_left);
    $branch->add($branch_right);
    
    $branch_left->add($leaf1);
    $branch_left->add($leaf2);
    
    print_r($branch);

    输出:

    Branch Object
    (
        [name] => 主干
        [node_list] => Array
            (
                [0] => Branch Object
                    (
                        [name] => 左树枝
                        [node_list] => Array
                            (
                                [0] => Leaf Object
                                    (
                                        [name] => 左第一片树叶
                                    )
    
                                [1] => Leaf Object
                                    (
                                        [name] => 左第二片树叶
                                    )
    
                            )
    
                    )
    
                [1] => Branch Object
                    (
                        [name] => 右树枝
                        [node_list] =>
                    )
    
            )
    
    )
  • 相关阅读:
    log4j的使用
    转:http与https
    转:归一化与正则化
    转:python 的开源库
    转:openTSDB 2.0 安装
    hadoop 2.2.0编译安装及打包
    查看磁盘信息
    HBase Region的flush过程
    HBase96的RPC
    阐述二维码的原理以及使用google api和PHP QR Code来生成二维码
  • 原文地址:https://www.cnblogs.com/itsuibi/p/10969327.html
Copyright © 2020-2023  润新知