Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

组合模式 #223

Open
louzhedong opened this issue Jun 24, 2020 · 0 comments
Open

组合模式 #223

louzhedong opened this issue Jun 24, 2020 · 0 comments

Comments

@louzhedong
Copy link
Owner

组合模式

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

定义如下:

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

优点:

高层模块调用简单

节点自由增加

缺点:

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

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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant