设计模式|组合模式
组合模式适合表示部分-整体, 例如大学-院系、部门-企业等。
代码
package com.elltor.designpattern.compose;
public abstract class Component {
protected String componentName;
public Component(String componentName) {
this.componentName = componentName;
}
public abstract void add(Component component);
public abstract void remove(Component component);
public abstract void show(int depth);
}
package com.elltor.designpattern.compose;
import java.util.ArrayList;
import java.util.List;
public class Composite extends Component {
private List<Component> childList = new ArrayList<>();
public Composite(String componentName) {
super(componentName);
}
@Override
public void add(Component component) {
childList.add(component);
}
@Override
public void remove(Component component) {
childList.remove(component);
}
@Override
public void show(int depth) {
for(int i=0;i<depth;i++){
System.out.print('+');
}
System.out.println(componentName);
for(int i=0;i<childList.size();i++){
childList.get(i).show(depth+2);
}
}
}
package com.elltor.designpattern.compose;
public class Leaf extends Component {
public Leaf(String componentName) {
super(componentName);
}
@Override
public void add(Component component) {
System.out.println("叶子节点无法增加节点");
}
@Override
public void remove(Component component) {
System.out.println("叶子节点无法删除节点");
}
@Override
public void show(int depth) {
for (int i = 0; i < depth; i++) {
System.out.print('+');
}
System.out.println(componentName);
}
}
package com.elltor.designpattern.compose;
public class Main {
public static void main(String[] args) {
Composite root = new Composite("树根");
root.add(new Leaf("叶子A"));
root.add(new Leaf("叶子B"));
Composite composite1 = new Composite("节点X");
composite1.add(new Leaf("叶子XA"));
composite1.add(new Leaf("叶子XB"));
Composite composite2 = new Composite("节点Y");
composite2.add(new Leaf("叶子YA"));
composite2.add(new Leaf("叶子YB"));
composite1.add(composite2);
root.add(composite1);
root.show(0);
}
}
// 打印
+树根
+++叶子A
+++叶子B
+++节点X
+++++叶子XA
+++++叶子XB
+++++节点Y
+++++++叶子YA
+++++++叶子YB