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
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有