一、简介
把一组相似的对象当作一个单一的对象,为的是减少数据类型
。
1、定义一个抽象对象,它可以表示两种或多种实际类型的对象
2、在对象内部,聚合一个抽象类型对象
3、构造时,递归这种联系
4、适合构造树形结构的对象关系
二、代码
代码中一般没有特殊情况,用一个叶子节点就可以了。
- 抽象基类
public abstract class Node {
private String name;
public Node(String name){
this.name = name;
}
public abstract List<Node> getChildren();
public String getName() {
return name;
}
}
- 尾节点
public class LeafNode extends Node{
public LeafNode(String name) {
super(name);
}
@Override
public List<Node> getChildren() {
return null;
}
}
- 中间节点
public class DistrictNode extends Node{
private List<Node> children = new ArrayList<>();
public DistrictNode(String name) {
super(name);
}
@Override
public List<Node> getChildren() {
return children;
}
public void addChild(Node node){
children.add(node);
}
public void delChild(int i){
children.remove(i);
}
}
- 测试
public class CompositeClient {
public static void main(String[] args){
sendFruit();
}
public static void sendFruit(){
//根目录
DistrictNode root = new DistrictNode("根");
//一线目录
root.addChild(new DistrictNode("上海"));
root.addChild(new DistrictNode("天津"));
DistrictNode districtNode = new DistrictNode("北京");
root.addChild(districtNode);
//二级目录
districtNode.addChild(new DistrictNode("海淀区"));
districtNode.addChild(new DistrictNode("西城区"));
DistrictNode districtNode2 = new DistrictNode("朝阳区");
districtNode.addChild(districtNode2);
//三级目录
districtNode2.addChild(new LeafNode("三里屯"));
districtNode2.addChild(new LeafNode("朝阳外街"));
System.out.println(JSON.toJSON(root));
//以下物流运输业务。。。。
}
}