java设计模式之组合模式(Composite)
时间:2021-09-01 09:01:55|栏目:JAVA代码|点击: 次
概述
是一种结构型模式,将对象以树形结构组织起来,以表示“部分 - 整体”的层次结构,使得客户端对单个对象和组合对象的使用具有唯一性。
UML类图

上面的类图包含的角色:
Component:为参加组合的对象声明一个公共的接口,不管是组合还是叶节点。
Leaf:在组合中表示叶子结点对象,叶子结点没有子结点。
Composite:表示参加组合的有子对象的对象,并给出树枝构建的行为;
代码示例
import java.util.ArrayList;
import java.util.List;
abstract class Component {
protected String name;
public Component(String name) {
this.name = name;
}
public abstract void Add(Component c);
public abstract void Remove(Component c);
public abstract void GetChild(int depth);
}
class Leaf extends Component {
public Leaf(String name) {
super(name);
}
@Override
public void Add(Component c) {
System.out.println("Can not add to a leaf");
}
@Override
public void Remove(Component c) {
System.out.println("Can not remove from a leaf");
}
@Override
public void GetChild(int depth) {
String temp = " ";
for (int i = 0; i < depth; i++) {
temp += "-";
System.out.println(temp + name);
}
}
}
class Composite extends Component {
private List<Component> children = new ArrayList<>();
public Composite(String name) {
super(name);
}
@Override
public void Add(Component c) {
children.add(c);
}
@Override
public void Remove(Component c) {
children.remove(c);
}
@Override
public void GetChild(int depth) {
for (Component c : children) {
c.GetChild(depth);
}
}
}
public class Main {
public static void main(String args[]) {
Composite root = new Composite("root");
root.Add(new Leaf("Leaf A"));
root.Add(new Leaf("Leaf B"));
Composite compX = new Composite("Composite X");
compX.Add(new Leaf("Leaf XA"));
compX.Add(new Leaf("Leaf XB"));
root.Add(compX);
Composite compXY = new Composite("Composite XY");
compXY.Add(new Leaf("Leaf XYA"));
compXY.Add(new Leaf("Leaf XYB"));
compX.Add(compXY);
root.GetChild(3);
}
}
应用场景
1.要求表示对象的部分-整体层次结构。
2.想要客户端忽略组合对象与单个对象的差异,客户端将统一地使用组合结构中的所有对象。
组合模式定义由Leaf对象和Composite对象组成的类结构;
使得客户端变得简单;
它使得添加或删除子部件变得很容易。


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




