设计模式之组合模式
组合模式
组合模式分为安全组合模式和透明组合模式,本文下的示例代码为透明组合模式,在叶子节点中冗余实现了叶子节点不需要的方法,而安全组合模式则需要进行叶子节点和普通节点的区分.
-
组合模式结构图
-
示例代码
// 抽象类
public abstract class Component {
protected String name;
public Component(String name) {
this.name = name;
}
public abstract void add(Component component);
public abstract void remove(Component component);
public abstract void display(int depth);
}
// 叶子节点
public class Leaf extends Component{
public Leaf(String name) {
super(name);
}
@Override
public void add(Component component) {
}
@Override
public void remove(Component component) {
}
@Override
public void display(int depth) {
for (int i = 0; i < depth; i++) {
System.out.print("-");
}
System.out.println(name);
}
}
// 普通节点
public class Composite extends Component{
private List<Component> list = new ArrayList<>();
public Composite(String name) {
super(name);
}
@Override
public void add(Component component) {
list.add(component);
}
@Override
public void remove(Component component) {
list.remove(component);
}
@Override
public void display(int depth) {
for (int i = 0; i < depth; i++) {
System.out.print("-");
}
System.out.println(name);
for (Component component : list) {
component.display(depth + 2);
}
}
}
// 测试
public class CompositeTest {
public static void main(String[] args) {
Component root = new Composite("root");
Component branch1 = new Composite("branch1");
Component branch2 = new Composite("branch2");
Component leaf1 = new Composite("leaf1");
Component branch11 = new Composite("branch11");
Component branch12 = new Composite("branch12");
Component branch13 = new Composite("branch13");
Component leaf21 = new Composite("leaf21");
Component leaf121 = new Composite("leaf121");
root.add(branch1);
root.add(branch2);
root.add(leaf1);
branch1.add(branch11);
branch1.add(branch12);
branch1.add(branch13);
branch12.add(leaf121);
branch2.add(leaf21);
root.display(2);
}
}
-
总结:
优点:清楚的定义了各层次的复杂对象,符合开闭原则;
缺点:限制类型时会较为复杂,使设计变得更加抽象.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
· Manus的开源复刻OpenManus初探