一、组合模式
允许你将对象组合成树形状结构来表现“整体/部分”的层次结构。组合能让客户以一致的方式处理个别对象以及组合。
二、举例
设计一个二级菜单
菜单组合类
package com.jackeys.Component;
import java.util.ArrayList;
/**
* @Description: 菜单组合类
* @ClassName: MenuComponet
* @Package com.jackeys.Component
* @Author: Jackeys 1623427047@qq.com
* @Copyright 版权归Jackeys企业(或个人)所有
* @CreateTime: 2021/10/25 9:16
* @Version: 1.0
*/
public class MenuComponent {
protected String name;
protected ArrayList<MenuComponent> menuComponents = new ArrayList<>();
public void add(MenuComponent component) throws Exception {
throw new Exception();
}
public void remove(MenuComponent component) throws Exception {
throw new Exception();
}
public MenuComponent getChild(int i) throws Exception {
throw new Exception();
}
public void print() throws Exception {
throw new Exception();
}
}
菜单类
package com.jackeys.Component;
/**
* @Description: 菜单类
* @ClassName: Menu
* @Package com.jackeys.Component
* @Author: Jackeys 1623427047@qq.com
* @Copyright 版权归Jackeys企业(或个人)所有
* @CreateTime: 2021/10/25 9:20
* @Version: 1.0
*/
public class Menu extends MenuComponent{
public Menu(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
@Override
public void add(MenuComponent component) {
this.menuComponents.add(component);
}
@Override
public void remove(MenuComponent component) {
this.menuComponents.remove(component);
}
@Override
public MenuComponent getChild(int i) {
return this.menuComponents.get(i);
}
@Override
public void print() {
System.out.println(this.name);
for (int i = 0; i < this.menuComponents.size(); i++) {
System.out.println(" " + this.menuComponents.get(i).name);
}
}
}
测试
package com.jackeys.Component;
/**
* @Description: 测试组合模式
* @ClassName: Test
* @Package com.jackeys.Component
* @Author: Jackeys 1623427047@qq.com
* @Copyright 版权归Jackeys企业(或个人)所有
* @CreateTime: 2021/10/25 9:24
* @Version: 1.0
*/
public class Test {
public static void main(String[] args) {
Menu personalCenter = new Menu("个人中心");
Menu personalInformation = new Menu("个人信息");
Menu accountInformation = new Menu("账号信息");
Menu myCollections = new Menu("我的收藏");
personalCenter.add(personalInformation);
personalCenter.add(accountInformation);
personalCenter.add(myCollections);
Menu systemManage = new Menu("系统管理");
Menu userManage = new Menu("用户管理");
Menu jurisdictionManage = new Menu("权限管理");
systemManage.add(userManage);
systemManage.add(jurisdictionManage);
personalCenter.print();
systemManage.print();
}
}
运行截图