模式的定义
组合模式(Composite Pattern):将对象组合成树形结构以表示"部分-整体"的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
组合模式,就是在一个对象中包含其他对象,这些被包含的对象可能是终点对象(不再包含别的对象),也有可能是非终点对象(其内部还包含其他对象,或叫组对象),我们将对象称为节点,即一个根节点包含许多子节点,这些子节点有的不再包含子节点,而有的仍然包含子节点,以此类推。
模式的结构
(1)抽象构件角色(Component):是组合中的对象声明接口,在适当的情况下,实现所有类共有接口的默认行为。这个接口可以用来管理所有的子对象。
(2)树枝构件角色(Composite):定义有子部件的那些部件的行为。在Component接口中实现与子部件有关的操作,构件和构件之间是可以嵌套的。
(3)树叶构件角色(Leaf):在组合树中表示叶节点对象,叶节点没有子节点。并在组合中定义图元对象的行为。
(4)客户角色(Client):通过Component接口操纵组合部件的对象。
模式的实现
抽象构件角色 Component.java
/*
* 抽象构件角色:是树枝构件角色和树叶构件角色的共同抽象
*/
public abstract class Component {
public abstract void add(Component component);//添加构件
public abstract void remove(Component component);//删除构件
public abstract void display(int depth);
}
树枝构件角色 Composite.java
/*
* 组件构件类
*/
public class Composite extends Component{
private String name;
private List<Component> ComponentList;
public Composite(String name) {
this.name = name;
this.ComponentList = new ArrayList<Component>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void display(int depth) {
StringBuffer strBuf = new StringBuffer("");
for (int i = 0; i < depth; i++) {
strBuf.append("--");
}
System.out.println(new String(strBuf) + this.getName());
for (Component c : ComponentList) {
//递归显示
c.display(depth + 2);
}
}
@Override
public void add(Component component) {
ComponentList.add(component);
}
@Override
public void remove(Component component) {
ComponentList.remove(component);
}
}
树叶构件角色 Leaf.java
/*
* 叶子构件类
*/
public class Leaf extends Component{
private String name;
public Leaf(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void display(int depth) {
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < depth; i++) {
sb.append("--");
}
System.out.println(new String(sb) + this.getName() ) ;
}
@Override
public void add(Component component) {
System.out.println("叶子节点不能添加构件...");
}
@Override
public void remove(Component component) {
System.out.println("叶子节点不能删除构件...");
}
}
客户角色 Client.java
/*
* 客户端
*/
public class Client {
public static void main(String[] args) {
/**
* 生成树根,跟上长出两叶LeafA 和 LeafB
*/
Composite root = new Composite("root");
root.add(new Leaf("LeafA"));
root.add(new Leaf("LeafB"));
/**
*跟上长出分枝CompositeX
* 分枝上有两叶LeafXA 和 LeafXB
*/
Composite comp = new Composite("CompositeX");
comp.add(new Leaf("LeafXA"));
comp.add(new Leaf("LeafXB"));
root.add(comp);
/**
* 显示树的结构
*/
root.display(0);
}
}
运行结果
(声明:本文为个人学习笔记,观点非原创。如有问题,欢迎讨论。)
参考文章: https://blog.csdn.net/disiwei1012/article/details/53513538
参考书:《大话设计模式》