zoukankan      html  css  js  c++  java
  • 设计模式09-组合模式

    1. 概念

             有时候又叫做部分-整体模式    存在整体和部分的时候  希望客户端忽略整体和部分的区别 

    2. 案例 

    /**********************************************************************
     * <pre>
     * FILE : Demo01.java
     * CLASS : Demo01
     *
     * AUTHOR : Liaokailin
     *
     * FUNCTION : TODO
     *
     *
     *======================================================================
     * CHANGE HISTORY LOG
     *----------------------------------------------------------------------
     * MOD. NO.|   DATE   |   NAME  | REASON  | CHANGE REQ.
     *----------------------------------------------------------------------
     *             |2014-3-5|Liaokailin| Created |
     * DESCRIPTION:
     * </pre>
     ***********************************************************************/
    package org.demo.composite;
    
    import java.util.ArrayList;
    import java.util.Iterator;
    
    /**
     * 存在整体和部分的时候  希望客户端忽略整体和部分的区别
     * Function : 
     * @author : Liaokailin
     * CreateDate : 2014-3-5
     * version : 1.0
     */
    public class Demo01 {
        @SuppressWarnings("unchecked")
        public static void main(String args[]){
            Node root = new Node("root") ;
            root.add(new Leaf("-leaf1")) ;
            Node c2 = new Node("-Node1") ;
            c2.add(new Leaf("--leaf2")) ;
            c2.add(new Leaf("--leaf3")) ;
            root.add(c2) ;
            c2 = new Node("-Node2");
            c2.add(new Leaf("--Leaf4"));
            c2.add(new Leaf("--Leaf5"));
            root.add(c2);
            root.operation() ;
        }
    }
    
    
    interface Component{
        void operation() ;
    }
    
    
    class Leaf implements Component{
        private String name  ;
        public Leaf(String name ){this.name = name ;}
        public String toString(){ return this.name ;}
        @Override
        public void operation() {
            System.out.println(this) ;
        }
    }
    
    class Node extends ArrayList implements Component{
        private String name ;
        public Node(String name){this.name = name ;}
        public String toString(){return this.name ;}
        @Override
        public void operation() {
            System.out.println(this) ;
            for(Iterator it = iterator() ;it.hasNext();){  // iterator() :获取集合中的元素
                ((Component)(it.next())).operation() ;
            }
        }
        
    }

    允许的结果: 

       

    root
    -leaf1
    -Node1
    --leaf2
    --leaf3
    -Node2
    --Leaf4
    --Leaf5
  • 相关阅读:
    进击的实时数仓:Flink 在 OPPO 实时计算平台的研发与应用实践
    vue中将时间戳转换为YYYY-MM-dd hh:mm格式时间的组件
    vue 将时间戳转换成日期格式 (一)
    element-ui DatePicker 日期选择器 让结束日期大于开始日期
    css 边框上如何写入文字?
    2019最新Web前端经典面试试题(含答案)
    Nginx 安装及配置
    前端基础面试题(JS部分)
    const与指针
    linux配置-------redhat虚拟机的中文输入法配置
  • 原文地址:https://www.cnblogs.com/liaokailin/p/3799930.html
Copyright © 2011-2022 走看看