整体与部分可以被一致对待
1.定义
将对像组合成树形结构以表示‘部分-整体’的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性。
2.代码示意
1)Component为组合中的对象声明接口,在适当的情况下,实现所有共有接口的默认行为。声明一个接口用于访问和管理component的子部件。
package designmode.component;
import interview.interfaccetest.C;
public abstract class Component {
protected String name;
public Component(String name){
this.name=name;
}
//使用Add和Remove方法提供增加或者移除树叶和树枝的功能
public abstract void add(Component c);
public abstract void remove(Component c);
public abstract void dislay(int depth);
}
2)Leaf表示叶节点对象,叶节点没有字节点
叶节点的Add和result并没有什么实际意义,实现只是为了消除叶节点和枝对象在抽象层次的区别
package designmode.component;
public class Leaf extends Component{
public Leaf(String name){
super(name);
}
@Override
public void add(Component c) {
System.out.println("叶子节点不能增加");
}
@Override
public void remove(Component c) {
System.out.println("叶子节点没有节点可以移除");
}
@Override
public void dislay(int depth) {
//叶节点的具体方法
System.out.println("-"+depth+name);
}
}
3)Composite定义有枝节点的行为,树枝节点用来存储子部件,在Component中实现与子部件有关的操作,比如增加add和删除Remove
package designmode.component;
import java.util.ArrayList;
import java.util.List;
//一个子对象集合用来存储其下属的枝节点和叶节点
public class Composite extends Component{
public Composite(String name){
super(name);
}
private List<Component> children=new ArrayList<Component>() ;
@Override
public void add(Component c) {
children.add(c);
}
@Override
public void remove(Component c) {
children.remove(c);
}
@Override
public void dislay(int depth) {
System.out.println("-"+depth+" "+name);
for(int i=0;i<children.size();i++){
children.get(i).dislay(depth+2);
}
}
}
4)客户端,能通过Component接口操作组合部件的对象
package designmode.component;
import interview.interfaccetest.C;
public class Client {
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 comp1=new Composite("Composite Xx");
comp1.add(new Leaf("Leaf XxA"));
comp1.add(new Leaf("Leaf XxB"));
comp.add(comp1);
Leaf leaf=new Leaf("叶子D");
root.add(leaf);
root.remove(leaf);
root.dislay(1);
}
}
运行结果
-1 root
-3Leaf A
-3Leaf B
-3 Composite X
-5Leaf XA
-5Leaf XB
-5 Composite Xx
-7Leaf XxA
-7Leaf XxB
上边的代码中,Componnet中声明所有用来管理子对象的方法,add和Remove等,使得所有实现Component抽象类的子类都有这些方法,但也没法避免的造成比如leaf类中也具有这些功能,但是没有什么意义。这种方式叫做透明方式。
如果不在 Component种实现所有功能,而是在Composite中声明所有用来管理子类对象的方法,就成为安全方式。这种方式的问题是因为不够透明,使得树叶和树枝不具有相同的接口,客户端的调用需要做响应的判断,带来了不便。
3.应用场景
当发现需求中体现部分与整体层次的结构时;
希望用户可以忽略组合对象与单个对象的不同,统一的使用组合结构中的所有对象时
4.优点
- 基本对象可以被组合成复杂的组合对象;
- 组合对象 又可以被组合,不断递归;
- 客户代码中,任何用到基本对象的地方都可以使用组合对象
- 用户不用关心到底时处理一个叶节点还是处理一个组合组件,也不用为定义组合而写一些选择判断语句;
- 组合模式使得客户可以一致的使用组合结构和单个对象;