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

javascript 设计模式(组合模式) #117

Open
wl05 opened this issue Apr 22, 2020 · 0 comments
Open

javascript 设计模式(组合模式) #117

wl05 opened this issue Apr 22, 2020 · 0 comments

Comments

@wl05
Copy link
Owner

wl05 commented Apr 22, 2020

概念

组合模式将所有对象组合成树形结构。使得用户只需要操作最上层的接口,就可以对所有成员做相同的操作。

实现

/******************************* Folder ******************************/
    var Folder = function (name) {
        this.name = name
        this.files = []
    }
    Folder.prototype.add = function (file) {
        this.files.push(file)
    }
    Folder.prototype.scan = function () {
        console.log('开始扫描文件夹: ' + this.name)
        for (var i = 0, file, files = this.files; file = files[i++];) {
            file.scan()
        }
    }
    /******************************* File ******************************/
    var File = function (name) {
        this.name = name
    }
    File.prototype.add = function () {
        throw new Error('文件下面不能再添加文件')
    }

    File.prototype.scan = function () {
        console.log('开始扫描文件: ' + this.name)
    }

    var folder = new Folder('学习资料')
    var folder1 = new Folder('JavaScript')
    var folder2 = new Folder('jQuery')
    var file1 = new File('JavaScript 设计模式与开发实践')
    var file2 = new File('精通 jQuery')
    var file3 = new File('重构与模式')
    folder1.add(file1)
    folder2.add(file2)
    folder.add(folder1)
    folder.add(folder2)
    folder.add(file3)
    var folder3 = new Folder('Nodejs')
    var file4 = new File('深入浅出 Node.js')
    folder3.add(file4)
    var file5 = new File('JavaScript 语言精髓与编程实践')
    folder.add(folder3)
    folder.add(file5)
    folder.scan()

参考资料

  1. JavaScript设计模式与开发实践-第七章-迭代器模式
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