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

    组合模式的定义:
    主要用来描述部分和整体的关系,其定义如下:
    Compose objects into tree structure to represent part-whole hierarchies. Composite lets clients treat
    individual objects and compositions of objects uniformly.
    将对象组合成树形结构以表示“部分——整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。

    组合模式的角色:
    1.Component抽象构件角色
    定义参加组合对象的共有方法和属性,可以定义一些默认的行为或属性
    2.Leaf叶子构件
    叶子对象,其下面也没有其他分支,也就是遍历的最小单位
    3.Composite树枝构件
    树枝对象,它的作用是组合树枝节点或叶子节点形成一个树形结构

    //抽象构件
    public abstract class Component{
        public void doSomething(){
            //
        }
    }
    //树枝构件
    public class Composite extends Component{
        private ArrayList<Component> componentArrayList=new ArrayList<Component>();
        public void add(Component component){
            this.componentArrayList.add(component);
        }
        public void remove(Component component){
            this.componentArrayList.remove(component);
        }
        public ArrayList<Component> getChildren(){
            return this.componentArrayList;
        }
    }
    
    //树叶构件
    public class Leaf extends Component{
        /*
         *可以覆盖父类方法
        public void doSomething(){
        
        }
        */
    }
    
    //场景类
    public class Client{
        public static void main(String[] args){
            //创建一个根节点
            Composite root=new Composite();
            root.doSomething();
            //构建一个树形节点
            Composite branch=new Composite();
            Leaf leaf=new Leaf();
            //建立整体
            root.add(branch);
            branch.add(leaf);
        }
        
        //通过递归遍历树
        public static void display(Composite root){
            for(Component c:root.getChildren()){
                if(c instanceof Leaf){//叶子节点
                    c.doSomething();
                }else{//树枝节点
                    display((Composite)c);
                }
            }
        }
    }
  • 相关阅读:
    什么是OOAD?什么是UML?
    Linux下Gvim 的基本操作-适合新手看
    关于mongodb ,redis,memcache之间见不乱理还乱的关系和作用
    phpcms常用标签
    请问如何更改dedecms“文件保存目录”的字符限制 ?
    如何通过刷百度指数来提高网站的权重
    HDU 1263(水果统计 **)
    HDU 1284(钱币兑换 背包/母函数)
    HDU 1028(数字拆分 分治)
    HDU 1036(平均速度 **)
  • 原文地址:https://www.cnblogs.com/liaojie970/p/5493147.html
Copyright © 2011-2022 走看看