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

    用于把一组相似的对象当作一个单一的对象

    涉及角色:
      1.Component 是组合中的对象声明接口,在适当的情况下,实现所有类共有接口的默认行为。声明一个接口用于访问和管理Component
    子部件。
      2.Leaf 在组合中表示叶子结点对象,叶子结点没有子结点。
      3.Composite 定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关操作,如增加(add)和删除

    Node

    package design.pattern.component;
    
    public abstract class Node {
        private String name;
        
        public Node(String name) {
            this.name = name;
        }
        public String getName() {
            return this.name;
        }
        public abstract Node addNode(Node node) throws RuntimeException;
        
        public void print(int depth) {
            for (int i=0; i<depth; i++)
                System.out.print(" ");
            
            System.out.println(this.name);
            
            if (this instanceof Menu) {
                for (Node node : ((Menu)this).getMenu()) {
                    node.print(depth+1);
                }
            }
        }
    }

    Item

    package design.pattern.component;
    
    public class Item extends Node {
    
        public Item(String name) {
            super(name);
        }
    
        @Override
        public Node addNode(Node node) throws RuntimeException {
            throw new RuntimeException();
        }
    
    }

    Menu

    package design.pattern.component;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class Menu extends Node {
        private List<Node> menu = new ArrayList<>();
        
        public Menu(String name) {
            super(name);
        }
    
        public List<Node> getMenu() {
            return menu;
        }
        @Override
        public Node addNode(Node node) throws RuntimeException {
            menu.add(node);
            return this;
        }
        
    }

    Client

    package design.pattern.component;
    
    public class Client {
        public static void main(String[] args) {
            Node menu = new Menu("1");
            menu.addNode(new Item("1.1"));
            menu.addNode(new Menu("1.2").addNode(new Item("1.2.1")));
            menu.addNode(new Item("1.3"));
            menu.print(0);
        }
    }
  • 相关阅读:
    Linux进入单用户模式(passwd root修改密码)
    stark组件的分页,模糊查询,批量删除
    stark组件的增删改(新)
    stark组件的增删改
    stark组件之展示数据(查)
    stark组件配置,二层URL
    单例模式及设计url分发
    Django之modelform
    rbac组件权限按钮,菜单,可拔插
    rbac权限+中间件
  • 原文地址:https://www.cnblogs.com/m2492565210/p/7461558.html
Copyright © 2011-2022 走看看