组合模式
package com.life.design.composite; public abstract class MenuComponent { protected String name; protected int level; public void add(MenuComponent menuComponent) { throw new UnsupportedOperationException(); } public void remove(MenuComponent menuComponent) { throw new UnsupportedOperationException(); } public MenuComponent getChild(int index) { throw new UnsupportedOperationException(); } public String getName() { return name; } public abstract void print(); }
package com.life.design.composite; import java.util.ArrayList; import java.util.List; public class Menu extends MenuComponent { private List<MenuComponent> menuComponentList = new ArrayList<>(); public Menu(String name,int level) { this.name = name; this.level = level; } @Override public void add(MenuComponent menuComponent) { menuComponentList.add(menuComponent); } @Override public void remove(MenuComponent menuComponent) { menuComponentList.remove(menuComponent); } @Override public MenuComponent getChild(int index) { return menuComponentList.get(index); } @Override public void print() { for (int i = 0; i < level; i++) { System.out.print(" "); } System.out.println(name); for (MenuComponent component : menuComponentList) { component.print(); } } }
package com.life.design.composite; public class MenuItem extends MenuComponent { public MenuItem(String name, int level) { this.name = name; this.level = level; } @Override public void print() { for (int i = 0; i < level; i++) { System.out.print(" "); } System.out.println(name); } }
package com.life.design.composite; public class Client { public static void main(String[] args) { MenuComponent menu1 = new Menu("菜单管理",2); menu1.add(new MenuItem("页面访问",3)); menu1.add(new MenuItem("展开菜单",3)); menu1.add(new MenuItem("编辑菜单",3)); menu1.add(new MenuItem("删除菜单",3)); menu1.add(new MenuItem("新增菜单",3)); MenuComponent menu2 = new Menu("权限管理",2); menu2.add(new MenuItem("页面访问",3)); menu2.add(new MenuItem("提交保存",3)); MenuComponent menu3 = new Menu("角色管理",2); menu3.add(new MenuItem("页面访问",3)); menu3.add(new MenuItem("新增角色",3)); menu3.add(new MenuItem("修改角色",3)); MenuComponent component = new Menu("系统管理",1); component.add(menu1); component.add(menu2); component.add(menu3); component.print(); } }