louzhedong / blog

前端基础,深入以及算法数据结构

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

组合模式

louzhedong opened this issue · comments

组合模式

组合模式也叫合成模式,有时又叫部分-整体模式

定义如下:

将对象组合成树形结构以表示“部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性

优点:

高层模块调用简单

节点自由增加

缺点:

未使用接口,直接使用实现类

Java
/**
 * 抽象构件
 **/
public abstract class Component {
    public void doSomething() {}
}

/**
 * 树枝构件
 **/
public class Composite extends Component{
    private ArrayList<Component> componentArrayList = new ArrayList<>();

    public void add(Component component) {
        this.componentArrayList.add(component);
    }

    public void remove(Component component) {
        this.componentArrayList.remove(component);
    }

    public ArrayList<Component> getChildren() {
        return this.componentArrayList;
    }
}

public class Leaf extends Component{
    @Override
    public void doSomething() {
    }
}

public class Client {
    public static void main(String[] args) {
        Composite root = new Composite();
        root.doSomething();

        Composite branch = new Composite();
        Leaf leaf = new Leaf();
        root.add(branch);
        branch.add(leaf);
    }

    public static void display(Composite root) {
        for (Component c: root.getChildren()) {
            if (c instanceof Leaf) {
                c.doSomething();
            } else {
                display((Composite)c);
            }
        }
    }
}
JavaScript
// 组合模式
var Folder = function (name) {
  this.name = name;
  this.files = [];
}

Folder.prototype.add = function (file) {
  this.files.push(file);
}

Folder.prototype.scan = function() {
  for (var i = 0, file, files = this.files; file = files[i++]) {
    file.scan();
  }
}


var File = function(name) {
  this.name = name;
}

File.prototype.scan = function() {}

var folder = new Folder("目录");
var file1 = new File("文件1");
var file2 = new File("文件2");

folder.add(file1);
folder.add(file2);

folder.scan();