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
  • 相关阅读:
    算法复习——扫描线(hdu1542)
    hbase简单操作
    python操作Mongo数据库
    查看图片大小
    python修改图片格式
    python图片压缩
    python 图片抓取
    failed to lazily initialize a collection of role: could not initialize proxy
    failed to lazily initialize a collection of role: could not initialize proxy
    vim自动打开跳到上次的光标位置
  • 原文地址:https://www.cnblogs.com/liaokailin/p/3799930.html
Copyright © 2011-2022 走看看