/**
* 組合模式協議.
*
* @author jialin.li
* @date 2019-12-20 15:22
*/
public abstract class AbstractComponent {
String name;
public AbstractComponent(String name) {
this.name = name;
}
public abstract void add(AbstractComponent c);
public abstract void remove(AbstractComponent c);
public abstract void display(int depth);
}
import java.util.ArrayList;
import java.util.List;
/**
* 組合模式中的枝葉,用來存儲子部件.
*
* @author jialin.li
* @date 2019-12-20 15:28
*/
public class Composite extends AbstractComponent {
private List<AbstractComponent> children = new ArrayList<>();
public Composite(String name) {
super(name);
}
@Override
public void add(AbstractComponent c) {
children.add(c);
}
@Override
public void remove(AbstractComponent c) {
children.remove(c);
}
@Override
public void display(int depth) {
for (int i = 0; i < depth; i++) {
System.out.print("-");
}
System.out.println(name);
for (AbstractComponent component : children) {
component.display(depth + 1);
}
}
}
/**
* 組合模式中的葉子節點.
*
* @author jialin.li
* @date 2019-12-20 15:26
*/
public class Leaf extends AbstractComponent {
public Leaf(String name) {
super(name);
}
@Override
public void add(AbstractComponent c) {
System.out.println("Cannot add a leaf!");
}
@Override
public void remove(AbstractComponent c) {
System.out.println("Cannot remove a leaf!");
}
@Override
public void display(int depth) {
for (int i = 0; i < depth; i++) {
System.out.print("-");
}
System.out.println(name);
}
}
/**
* 客戶端.
*
* @author jialin.li
* @date 2019-12-20 15:33
*/
public class Main {
public static void main(String[] args) {
Composite root = new Composite("root");
root.add(new Leaf("Leaf A"));
root.add(new Leaf("Leaf B"));
Composite comp = new Composite("Composite X");
comp.add(new Leaf("Leaf XA"));
comp.add(new Leaf("Leaf XB"));
root.add(comp);
Composite comp2 = new Composite("Composite XY");
comp2.add(new Leaf("Leaf XYA"));
comp2.add(new Leaf("Leaf XYB"));
comp.add(comp2);
root.add(new Leaf("Leaf C"));
Leaf d = new Leaf("D");
root.add(d);
root.remove(d);
root.display(1);
}
}
-root
--Leaf A
--Leaf B
--Composite X
---Leaf XA
---Leaf XB
---Composite XY
----Leaf XYA
----Leaf XYB
--Leaf C
engine表示引擎,一個Service最多隻能有一個引擎,Host表示虛擬主機、Context表示一個Web應用、Wrapper表示一個Servlet(後三種容器能夠有多個)