组合模式 (Component)
用途
将对象组合成树形结构以表示“部分-整体”的层次结构。
组合模式使得用户对单个对象和组合对象的使用具有唯一性。
组合模式是一种结构型模式。
结构
Component : 组合中的对象声明接口,在适当的情况下,实现所有类共有接口的默认行为。声明一个接口用于访问和管理 Component 的子部件。
public abstract class Component {
protected String name;
public Component(String name){
this.name = name;
}
public abstract void add(Component component);
public abstract void remove(Component component);
public abstract void display(int depth);
}
Leaf : 表示叶节点对象。叶子节点没有子节点。
class Leaf extends Component{
public Leaf(String name){
super(name);
}
@Override
public void add(Component component) {
System.out.println("can not add to leaf");
}
@Override
public void remove(Component component) {
System.out.println("can not remove from leaf");
}
@Override
public void display(int depth) {
String temp = "";
for(int i = 0;i < depth;i++){
temp += "-";
}
System.out.println(temp + name);
}
}
Composite : 定义枝节点行为,用来存储子部件,在 Component 接口中实现与子部件相关的操作。例如 Add 和 Remove。
class Composite extends Component{
private List<Component> children = new ArrayList<>();
public Composite(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 display(int depth) {
String temp = " ";
for(int i = 0;i < depth;i++){
temp += "-";
}
System.out.println(temp + name);
for(Component c:children){
c.display(depth + 2);
}
}
}
Client:
public class Client {
public static void main(String[] args) {
Component c1,c2,c3,c4,c5;
c1 = new Leaf("v1");
c2 = new Leaf("c2");
c3 = new Leaf("c3");
c4 = new Composite("C4");
c5 = new Composite("C5");
c4.add(c1);
c4.add(c2);
c4.add(c3);
c5.add(c4);
//c1.display(3);
//c4.display(5);
c5.display(6);
}
}
应用场景
1、想要表示对象的部分-整体层次结构。
2、想要客户端忽略组合对象与单个对象的差异,客户端将统一地使用组合结构中的所有对象。
关于分级数据结构的一个普遍性的例子是你每次使用电脑时所遇到的:文件系统。
文件系统由目录和文件组成。每个目录都可以装内容。目录的内容可以是文件,也 可以是目录。
按照这种方式,计算机的文件系统就是以递归结构来组织的。如果你想要描述这样的数据结构,那么你可以使用组合模式。
要点
组合模式定义由 Leaf 对象和 Composite 对象组成的类结构;
它使得客户端变得简单;
它使得添加或删除子部件变得很容易。