组合模式定义:
组合模式,将对象组合成树形结构以表示“部分-整体”的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性。掌握组合模式的重点是要理解清楚 “部分/整体” 还有 ”单个对象“ 与 "组合对象" 的含义。
组合模式可以让客户端像修改配置文件一样简单的完成本来需要流程控制语句来完成的功能。
组合模式使用场景
- 场景一:表示对象整体和局部结构的时候,需要使用组合模式。
- 场景二:从一个整体中能够独立出部分模块或者功能的场景下,我们可以使用组合模式。
经典案例:系统目录结构,网站导航结构等。
组合模式角色划分
角色一:抽象根节点(抽象类、接口)->Component
角色二:具体子节点->Composite
角色三:叶子节点(注意:没有儿子->没有子节点)->Leaf
原型案例
角色一:抽象节点
public abstract class Component {
//节点名称
private String nodeName;
public Component(String nodeName){
this.nodeName = nodeName;
}
public String getNodeName() {
return nodeName;
}
//定义一些业务逻辑
public abstract void doSomeThing();
}
角色二:具体节点
public class Composite extends Component {
private List<Component> componentList = new ArrayList<Component>();
public Composite(String nodeName) {
super(nodeName);
}
@Override
public void doSomeThing() {
System.out.println("具体节点:");
System.out.println(getNodeName());
for (Component component : componentList) {
System.out.println(getNodeName()+"->"+component.getNodeName());
}
}
public void addChild(Component child) {
this.componentList.add(child);
}
public void removeChild(Component child) {
this.componentList.remove(child);
}
public Component getComponent(int index) {
return this.componentList.get(index);
}
}
角色三:叶子节点
public final class Leaf extends Component {
public Leaf(String nodeName) {
super(nodeName);
}
@Override
public void doSomeThing() {
System.out.println("叶子节点");
}
}
客户端
public class Client {
public static void main(String[] args) {
Composite root = new Composite("总公司");
root.addChild(new Leaf("子公司1"));
root.addChild(new Leaf("子公司2"));
root.addChild(new Leaf("子公司3"));
root.doSomeThing();
}
}
以上便是组合模式的基本使用,在Android中,ViewGroup便是组合模式的实例案例。
文章有误之处,望众大神在留言区指出,谢谢!