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);
                }
            }
        }
    }
  • 相关阅读:
    php分页类
    jquery Deferred对象
    sql 常见面试题
    C# socket编程第二篇
    Sqlserver本地服务启动不了,提示请求失败或服务未及时响应
    Sqlserver函数之log,power,len
    C#除法
    C# socket编程第一篇
    android菜鸟进修之路一layout里添加xml文件没有在R.java里生成ID
    form提交时应注意“&”符号
  • 原文地址:https://www.cnblogs.com/liaojie970/p/5493147.html
Copyright © 2011-2022 走看看