1.安全写法规定相对于透明写法而言,顶层的抽象中只包含必要的细节。不用实现不要的方法,具体细节在子类实现中实现。
2.顶层抽象Root
public abstract class Root {
String name;
public Root(String name) {
this.name = name;
}
public abstract void show();
}
分支节点
package com.dxy;
import java.util.ArrayList;
import java.util.List;
/**
* @author dxy
* @version 1.0
* @date 2021/3/29 15:45
* @Description 树枝节点可能又叶子和别的分支
*/
public class Branch extends Root {
//节点等级
private Integer level;
//子节点集合
private List<Root> subs;
public Branch(String name, Integer level) {
super(name);
this.level = level;
this.subs = new ArrayList();
}
@Override
public void show() {
System.out.println("====我是树枝节点--》name:=>" + this.name);
subs.forEach(e -> {
if (this.level != null) {
for (int i = 0; i < this.level; i++) {
//显示格式前面空格
System.out.print(" ");
}
for (int i = 0; i < this.level; i++) {
if (i == 0) {
System.out.print("+");
}
System.out.print("-");
}
}
e.show();
});
}
public void addChild(Root child) {
subs.add(child);
}
public void removeChild(Root child) {
subs.remove(child);
}
public Root getOne(Integer i) {
return this.subs.get(i);
}
public void list() {
this.subs.forEach(e -> System.out.println(e.name));
}
}
叶子节点
public class Leaf extends Root {
public Leaf(String name) {
super(name);
}
@Override
public void show() {
System.out.println("我是叶子-->name:" + this.name);
}
}
测试方法
public static void main(String[] args) {
//叶子节点
Leaf leafqq = new Leaf("qq.exe");
Leaf leafwechat = new Leaf("wechat.exe");
Branch branch1 = new Branch("聊天工具",2);
branch1.addChild(leafqq);
branch1.addChild(leafwechat);
Leaf idea = new Leaf("alipay.exe");
Leaf nodepad = new Leaf("baidu.exe");
Leaf eclipse = new Leaf("sina.exe");
Branch branch2 = new Branch("开发工具",2);
branch2.addChild(idea);
branch2.addChild(nodepad);
branch2.addChild(eclipse);
Leaf pdf = new Leaf("pdf.exe");
Leaf ppt = new Leaf("ppt.exe");
Leaf wps = new Leaf("wps.exe");
Branch branch3 = new Branch("办公软件",2);
Branch branch4 = new Branch("国产软件",3);
Branch branch5 = new Branch("非国产软件",3);
branch4.addChild(wps);
branch5.addChild(pdf);
branch5.addChild(ppt);
branch3.addChild(branch4);
branch3.addChild(branch5);
//根
Branch root = new Branch("根目录",1);
root.addChild(branch1);
root.addChild(branch2);
root.addChild(branch3);
root.show();
}
结果