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
  • 相关阅读:
    DNS原理总结及其解析过程详解
    linux修改进程名
    mq_open失败,Invalid argument
    Posix消息队列
    undefined reference to 'mq_open'
    量化投资学习笔记08——统计学基础补漏
    量化投资学习笔记07——python知识补漏
    量化投资学习笔记06——《打开量化投资的黑箱》读书笔记
    量化投资学习笔记05——检验计算回测指标程序
    量化投资学习笔记04——回测实盘策略
  • 原文地址:https://www.cnblogs.com/liaokailin/p/3799930.html
Copyright © 2011-2022 走看看