package com.jmj.pattern.combination;/*** 菜单组件,属于抽象根节点*/
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.jmj.pattern.combination;/*** 菜单项类*/
public class MenuItem extends MenuComponent {public MenuItem(String name, int level) {this.name = name;this.level = level;}@Overridepublic void print() {for (int i = 0; i < level; i++) {System.out.print("--");}//打印菜单项名称System.out.println(name);}
}
package com.jmj.pattern.combination;import java.util.ArrayList;
import java.util.List;public class Menu extends MenuComponent{//菜单可以有多个子菜单或者子菜单项private List<MenuComponent> menuComponents =new ArrayList<>();public Menu(String name,int level) {this.name=name;this.level=level;}@Overridepublic void add(MenuComponent menuComponent) {menuComponents.add(menuComponent);}@Overridepublic void remove(MenuComponent menuComponent) {menuComponents.remove(menuComponent);}@Overridepublic MenuComponent getChild(int index) {return menuComponents.get(index);}@Overridepublic void print() {for (int i = 0; i < level; i++) {System.out.print("--");}//打印菜单名称System.out.println(name+":");//打印子菜单或者子菜单项名称for (MenuComponent menuComponent : menuComponents) {menuComponent.print();}}}
package com.jmj.pattern.combination;public class Client {public static void main(String[] args) {MenuComponent menu = new Menu("菜单管理", 2);menu.add(new MenuItem("页面访问",3));menu.add(new MenuItem("展开菜单",3));menu.add(new MenuItem("编辑菜单",3));menu.add(new MenuItem("删除访问",3));menu.add(new MenuItem("新增访问",3));MenuComponent menu1 = new Menu("权限管理", 2);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));menu2.add(new MenuItem("修改角色",3));//创建一级菜单系统管理MenuComponent m = new Menu("系统管理", 1);m.add(menu);m.add(menu1);m.add(menu2);//打印菜单名称m.print();}
}