八、结构型(组合模式)
// 抽象构件(透明组合)
interface Component {
void operation();
void add(Component component);
void remove(Component component);
Component getChild(int i);
}
// 叶子节点(透明组合)
class Leaf implements Component {
private String name;
public Leaf(String name) {
this.name = name;
}
@Override
public void operation() {
System.out.println("叶子 " + name + " 被访问");
}
@Override
public void add(Component component) {
throw new UnsupportedOperationException("叶子节点不支持添加操作");
}
@Override
public void remove(Component component) {
throw new UnsupportedOperationException("叶子节点不支持删除操作");
}
@Override
public Component getChild(int i) {
throw new UnsupportedOperationException("叶子节点没有子节点");
}
}
// 组合节点(透明组合)
class Composite implements Component {
private List<Component> children = new ArrayList<>();
@Override
public void operation() {
System.out.println("组合节点被访问");
for (Component child : children) {
child.operation();
}
}
@Override
public void add(Component component) {
children.add(component);
}
@Override
public void remove(Component component) {
children.remove(component);
}
@Override
public Component getChild(int i) {
return children.get(i);
}
}
// 客户端
public class ClientTransparentComposite {
public static void main(String[] args) {
Component leaf1 = new Leaf("1");
Component leaf2 = new Leaf("2");
Component leaf3 = new Leaf("3");
Composite composite = new Composite();
composite.add(leaf1);
composite.add(leaf2);
Composite root = new Composite();
root.add(composite);
root.add(leaf3);
root.operation();
}
}