组合模式(Composite Pattern)
提供demo版代码更容易理解
/**
* @author zhou
* 组件抽象类
*/
abstract class Component {
protected String name;
public Component(String name) {
this.name = name;
}
public abstract void operation();
// 可以选择在组件类中提供默认实现,简化容器类的实现
public void add(Component component) {
throw new UnsupportedOperationException();
}
public void remove(Component component) {
throw new UnsupportedOperationException();
}
public Component getChild(int index) {
throw new UnsupportedOperationException();
}
}
/**
* @author zhou
* 容器类
*/
class Composite extends Component {
private List<Component> children = new ArrayList<>();
public Composite(String name) {
super(name);
}
@Override
public void operation() {
System.out.println("Composite " + name + ": Operation");
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 index) {
return children.get(index);
}
}
/**
* @author zhou
* 叶子类
*/
class Leaf extends Component {
public Leaf(String name) {
super(name);
}
@Override
public void operation() {
System.out.println("Leaf " + name + ": Operation");
}
}
/**
* @author zhou
* 客户端使用
*/
public class Main {
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");
Leaf leaf3 = new Leaf("leaf3");
Leaf leaf4 = new Leaf("leaf4");
// 组合对象添加子节点
root.add(branch1);
root.add(branch2);
branch1.add(leaf1);
branch1.add(leaf2);
branch2.add(leaf3);
branch2.add(leaf4);
// 调用组合对象的操作
root.operation();
}
}