设计模式之组合模式

2017-06-13  本文已影响30人  老羊_肖恩

组合模式的定义

组合模式(Composite Pattern)也叫合成模式,有时候也叫整体-部分模式,主要用来描述整体和部分之间的关系,其定义如下:
  Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. 即:将对象组合成树形结构以表示“部分-整体”的层次关系,是的用户对单个对象和组合对象的使用具有一致性。
组合模式的通用类图如下:

Component.jpg

组合模式的几个角色如下:

组合模式的通用代码如下:

import java.util.ArrayList;

//抽象构件
public abstract class Component{
    //部分和整体共享的业务逻辑
    public abstract void doSomething();
}

//整体构件
public class Composite extends Component{
    //构件容器
    private ArrayList<Component> leafsList = new ArrayList<Component>();
    
    //添加叶子构件或树枝构件
    public void add(Component component){
        System.out.println("add component...");
        this.leafsList.add(component);
    }
    
    //删除叶子节点或树枝构件
    public void remove(Component component){
        System.out.println("remove component...");
        this.leafsList.remove(component);
    }
    
    //获得分之下的所有叶子或树枝构件
    public ArrayList<Component> getChildren(){
        return this.leafsList;
    }
    
    //整体构件的业务逻辑
    @Override
    public void doSomething() {
        System.out.println("Composite doSomething...");
    }
    
}

//树叶构件
public class Leaf extends Component{

    @Override
    public void doSomething() {
        System.out.println("Leaf doSomething...");
    }
    
}

//客户端
public class ComponentClient{
    public static void main(String[] args) {
        Composite root = new Composite();
        root.doSomething();
        //创建一个树枝构件
        Composite branch = new Composite();
        Leaf leaf = new Leaf();
        
        branch.add(leaf);
        root.add(branch);
        
        display(root);
    }
    //通过递归遍历树
    public static void display(Composite root){
        for(Component c:root.getChildren()){
            if(c instanceof Leaf){
                c.doSomething();
            }else{
                display((Composite) c);
            }
        }
    }
}

代码运行结果如下:

Composite doSomething...
add component...
add component...
Leaf doSomething...

组合模式的应用

组合模式的优点

组合模式的缺点

组合模式使用场景

《注》以上内容总结自秦小波-《设计模式之禅》,仅为个人学习笔记

上一篇 下一篇

猜你喜欢

热点阅读