定义
In software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes a group of objects that are treated the same way as a single instance of the same type of object. The intent of a composite is to “compose” objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly. —Wikipedia
结构
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Pn2eiakW-1582554010549)(https://s3-us-west-2.amazonaws.com/secure.notion-static.com/fc26a8f2-54ad-4298-bd34-b10765f7bc82/Untitled.png)]](https://i-blog.csdnimg.cn/blog_migrate/9614ad6cfdc986a8864012283d30e6f1.png)
Demo
import java.util.ArrayList;
import java.util.List;
abstract class Node {
abstract public void p();
}
class LeafNode extends Node {
String content;
public LeafNode(String content) {this.content = content;}
@Override
public void p() {
System.out.println(content);
}
}
class BranchNode extends Node {
List<Node> nodes = new ArrayList<>();
String name;
public BranchNode(String name) {this.name = name;}
@Override
public void p() {
System.out.println(name);
}
public void add(Node n) {
nodes.add(n);
}
}
public class Main {
public static void main(String[] args) {
BranchNode root = new BranchNode("root");
BranchNode chapter1 = new BranchNode("chapter1");
BranchNode chapter2 = new BranchNode("chapter2");
Node r1 = new LeafNode("r1");
Node c11 = new LeafNode("c11");
Node c12 = new LeafNode("c12");
BranchNode b21 = new BranchNode("section21");
Node c211 = new LeafNode("c211");
Node c212 = new LeafNode("c212");
root.add(chapter1);
root.add(chapter2);
root.add(r1);
chapter1.add(c11);
chapter1.add(c12);
chapter2.add(b21);
b21.add(c211);
b21.add(c212);
//递归打印树
tree(root, 0);
}
static void tree(Node b, int depth) {
//每进一层,则多打印一个'-'
for(int i=0; i<depth; i++) System.out.print("-");
b.p();
if(b instanceof BranchNode) {
for (Node n : ((BranchNode)b).nodes) {
tree(n, depth + 1);
}
}
}
}
输出:
root
-chapter1
--c11
--c12
-chapter2
--section21
---c211
---c212
-r1
总结
树状结构 - 组合模式
本文深入探讨了软件工程中的组合模式,通过Java代码示例展示了如何使用该模式构建树状结构来表示部分-整体层次关系,使得客户端可以统一处理单个对象和组合。
1833

被折叠的 条评论
为什么被折叠?



