Component.java
package com.godv.composite;
//叶子节点和根节点的抽象类
public abstract class Component {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// 提供一个add方法用来构建树
public void add(Component component) {
throw new UnsupportedOperationException();
}
public void remove(Component component) {
throw new UnsupportedOperationException();
}
// 打印方法 类似于叶子节点和根节点都需要重写的方法
public abstract void print();
}
University.java 根节点
package com.godv.composite;
import java.util.ArrayList;
import java.util.List;
public class University extends Component {
private List<Component> mList = new ArrayList<>();
@Override
public String getName() {
// TODO Auto-generated method stub
return super.getName();
}
@Override
public void setName(String name) {
// TODO Auto-generated method stub
super.setName(name);
}
@Override
public void add(Component component) {
// TODO Auto-generated method stub
mList.add(component);
}
@Override
public void remove(Component component) {
// TODO Auto-generated method stub
mList.remove(component);
}
@Override
public void print() {
// TODO Auto-generated method stub
System.out.println(getName());
for (Component component : mList) {
component.print();
}
}
}
Department.java 叶子节点 叶子节点不需要再有子节点
package com.godv.composite;
public class Department extends Component{
@Override
public String getName() {
// TODO Auto-generated method stub
return super.getName();
}
@Override
public void setName(String name) {
// TODO Auto-generated method stub
super.setName(name);
}
@Override
public void print() {
// TODO Auto-generated method stub
System.out.println(getName());
}
}
Client.java
package com.godv.composite;
public class Client {
public static void main(String[] args) {
Component university = new University();
university.setName("清华大学");
Component university2 = new University();
university2.setName("计算机学院");
Department department = new Department();
department.setName("软件工程");
Department department2 = new Department();
department2.setName("通信工程");
university.add(university2);
university2.add(department);
university2.add(department2);
university.print();
}
}