Java 中组合模型之对象结构模式的详解
时间:2021-02-17 14:01:22|栏目:JAVA代码|点击: 次
Java 中组合模型之对象结构模式的详解
一、意图
将对象组合成树形结构以表示”部分-整体”的层次结构。Composite使得用户对单个对象和组合对象的使用具有一致性。
二、适用性
你想表示对象的部分-整体层次结构
你希望用户忽略组合对象与单个对象的不同,用户将统一使用组合结构中的所有对象。
三、结构

四、代码
public abstract class Component {
protected String name; //节点名
public Component(String name){
this.name = name;
}
public abstract void doSomething();
}
public class Composite extends Component {
/**
* 存储节点的容器
*/
private List<Component> components = new ArrayList<>();
public Composite(String name) {
super(name);
}
@Override
public void doSomething() {
System.out.println(name);
if(null!=components){
for(Component c: components){
c.doSomething();
}
}
}
public void addChild(Component child){
components.add(child);
}
public void removeChild(Component child){
components.remove(child);
}
public Component getChildren(int index){
return components.get(index);
}
}
public class Leaf extends Component {
public Leaf(String name) {
super(name);
}
@Override
public void doSomething() {
System.out.println(name);
}
}
public class Client {
public static void main(String[] args){
// 构造一个根节点
Composite root = new Composite("Root");
// 构造两个枝干节点
Composite branch1 = new Composite("Branch1");
Composite branch2 = new Composite("Branch2");
// 构造两个叶子节点
Leaf leaf1 = new Leaf("Leaf1");
Leaf leaf2 = new Leaf("Leaf2");
branch1.addChild(leaf1);
branch2.addChild(leaf2);
root.addChild(branch1);
root.addChild(branch2);
root.doSomething();
}
}
输出结果:
Root
Branch1
Leaf1
Branch2
Leaf2
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!


阅读排行
- 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虚拟机




