一、定义
组合模式将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
二、框架运用
springMVC通过组合模式,使得用户或者说框架本身在进行配置时,就通过操作WebMvcConfigurer类及其衍生类这个整体就行了
三、实战
1、抽象类
public abstract class Component {
protected String name;
public Component(String name) {
this.name = name;
}
public Component() {
}
public abstract void add(Component component);
public abstract void remove(Component component);
public abstract void showContent();
}
2、实现类
public class Leaf extends Component {
public Leaf(String name) {
super(name);
}
@Override
public void add(Component component) {
System.out.println("叶子节点不能增加下级");
}
@Override
public void remove(Component component) {
System.out.println("叶子节点不能删除下级");
}
@Override
public void showContent() {
System.out.println("叶子节点:"+name);
}
}
public class Compsite extends Component {
private List<Component> children = new ArrayList<>();
public Compsite(String name) {
super(name);
}
@Override
public void add(Component component) {
children.add(component);
}
@Override
public void remove(Component component) {
children.remove(component);
}
@Override
public void showContent() {
System.out.println("树干节点:"+name);
children.forEach(Component::showContent);
}
}
3、运行和结果
public class Client {
public static void main(String[] args) {
Compsite root = new Compsite("根");
root.add(new Leaf("树叶A"));
root.add(new Leaf("树叶B"));
Compsite siteA = new Compsite("树干A");
Compsite siteB = new Compsite("树干B");
Compsite siteC = new Compsite("树干C");
siteA.add(new Leaf("树叶C"));
siteA.add(new Leaf("树叶D"));
siteC.add(new Leaf("树叶E"));
siteC.add(new Leaf("树叶F"));
siteB.add(siteC);
root.add(siteA);
root.add(siteB);
root.showContent();
siteB.remove(siteC);
System.out.println("---------------------分隔符--------------------");
root.showContent();
}
}
Connected to the target VM, address: '127.0.0.1:49611', transport: 'socket'
树干节点:根
叶子节点:树叶A
叶子节点:树叶B
树干节点:树干A
叶子节点:树叶C
叶子节点:树叶D
树干节点:树干B
树干节点:树干C
叶子节点:树叶E
叶子节点:树叶F
---------------------分隔符--------------------
树干节点:根
叶子节点:树叶A
叶子节点:树叶B
树干节点:树干A
叶子节点:树叶C
叶子节点:树叶D
树干节点:树干B
Disconnected from the target VM, address: '127.0.0.1:49611', transport: 'socket'