java实现23种设计模式之组合模式

组合模式有时又叫部分-整体模式在处理类似树形结构的问题时比较方便

package com.ceshi10;

import java.util.Enumeration;
import java.util.Vector;

public class TreeNode {
    private String name;
    private TreeNode parent;
    private Vector<TreeNode> children = new Vector<TreeNode>();
    
    public TreeNode(String name){
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public TreeNode getParent() {
        return parent;
    }

    public void setParent(TreeNode parent) {
        this.parent = parent;
    }
    
    //添加孩子节点
    public void add(TreeNode node){
        children.add(node);
    }
    
    //删除孩子节点
    public void remove(TreeNode node){
        children.remove(node);
    }
    
    //取得孩子节点
    public Enumeration<TreeNode> getChildren(){
        return children.elements();
    }
}
package com.ceshi10;

import java.util.Enumeration;

public class Tree {
    TreeNode root = null;

    public Tree(String name) {
        root = new TreeNode(name);
    }

    public static void main(String[] args) {
        Tree tree = new Tree("A");
        TreeNode nodeB = new TreeNode("B");
        TreeNode nodeC = new TreeNode("C");
        TreeNode nodeD = new TreeNode("D");
        
        nodeB.add(nodeC);
        nodeC.setParent(nodeB);
        nodeB.add(nodeD);
        nodeD.setParent(nodeB);
        tree.root.add(nodeB);
        nodeB.setParent(tree.root);
        System.out.println("完成建树!");
        TreeNode treeNode = tree.root;
        getTree(treeNode);
    }
    
    public static void getTree(TreeNode treeNode){
        if(treeNode.getChildren().hasMoreElements()){
            getTree(treeNode.getChildren().nextElement());
        }else{
            System.out.println(treeNode.getName());
            if(treeNode.getParent()!=null){
                treeNode.getParent().remove(treeNode);
                getTree(treeNode.getParent());
            }
        }
    }
}

结果:

使用场景:将多个对象组合在一起进行操作,常用于表示树形结构中,例如二叉树,数等。

posted @ 2019-04-22 15:22  十黎九夏  阅读(344)  评论(0编辑  收藏  举报