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;
}
@Override
public 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;
}
@Override
public void add(MenuComponent menuComponent) {
menuComponents.add(menuComponent);
}
@Override
public void remove(MenuComponent menuComponent) {
menuComponents.remove(menuComponent);
}
@Override
public MenuComponent getChild(int index) {
return menuComponents.get(index);
}
@Override
public 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();
}
}