zoukankan      html  css  js  c++  java
  • 二十三种设计模式之:组合(Composite)模式(部分·整体模式)

    组合(Composite)模式又叫部分·整体模式,主要用于实现树形结构。

    例子如下:

    public class TreeNode{

      private TreeNode parent;

      private String name;

      private List<TreeNode> children = new Arraylist<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 addChildren(TreeNode childrenNode){

        children.add(childrenNode);

      }

      //删除子节点

      public void removeChildren(TreeNode childrenNode){

        children.remove(childrenNode);

      }

      //取得孩子节点

      public Enumeration<TreeNode> getChildrenNode(){

        children.elements();

      }

    }

    测试类:

    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 rootNode = new TreeNode("B");

        TreeNode childrenNode = new TreeNode("C");

            rootNode.addChildren(childrenNode);

        tree.root.addChildren(rootNode);

        System.out.println("Build the tree finished!");

      }

    }

  • 相关阅读:
    自定义Android Toasts风格
    用TAPI实现来电拒接
    压缩与解压缩的实现
    Android之个性化ListView实现
    如何在windows7 Home家庭版中创建Administrator管理员账户
    Android中Intent传递对象的两种方法(Serializable,Parcelable)
    Android模拟器入门
    上海西门子培训第六天(周五)
    上海西门子培训第七天(周六)
    计算机英语学习方法[摘录]
  • 原文地址:https://www.cnblogs.com/qadyyj/p/5670254.html
Copyright © 2011-2022 走看看