JavaScript組合模式學習要點_javascript技巧

來源:互聯網
上載者:User

組合模式:將一組對象組合成樹形結構,並統一對待組合對象和葉對象,忽略它們之間的不同(因為葉對象也可以也可以包含葉對象而成為組合對象),組合模式中的對象只能是一對多的關係,不能出現多對一。

基本單元:一個組合對象包含多個葉對象。每個基本單元又可以是別的組合對象的葉對象類似檔案夾與它裡面的內容的關係網,一個檔案夾或檔案又可以是其它檔案夾的內容,但一個檔案夾或檔案不能同時屬於多個上級檔案夾。

在JavaScript中實現組合模式時,要保證組合對象和葉對象擁有相同的介面方法,對同一組葉對象的操作必須具有一致性。

例子:

//定義組合對象var Folder = function (name) {this.name = name;this.parent = null;this.files = [];};Folder.prototype.add = function (file) {file.parent = this;if(this.files.indexOf(file) === -1){this.files.push(file);}else{console.log('\''+file.name+'\'已存在,添加失敗');}};Folder.prototype.scan = function () {if(this.parent){console.log('開始掃描\''+this.parent.name+'\': '+this.name);}else{console.log('開始掃描根目錄: '+this.name);}//關鍵在這裡,調用所有它的葉對象的介面方法scan()for(var i = 0, file; file = this.files[i++];){file.scan();}};Folder.prototype.remove = function (file) {var n = this.files.indexOf(file);if(n === -1){console.log('無法刪除: \''+file.name+'\'不存在:');}if(n >= 0){this.files.splice(n,1);console.log('成功刪除:'+file.name);}};//定義葉對象var File = function (name) {this.name = name;this.parent = null;};File.prototype.add = function () {console.log('不能添加在檔案下面');};File.prototype.scan = function () {console.log(this.parent.name+': '+this.name);};File.prototype.remove = function (file) {console.log('無法刪除: \''+file.name+'\'不存在:');};//測試var folder = new Folder('目錄');var folder1 = new Folder('學習質料');var folder2 = new Folder('javascript');var file1 = new File('Node.js');var file2 = new File('qq.jpg');folder.add(folder1);folder.add(folder1);folder.add(folder2);folder1.add(file1);folder2.add(file2);//'學習質料'添加成功//'學習質料'已存在,添加失敗//'javascript'添加成功//'Node.js'添加成功//'qq.jpg'添加成功folder.remove(folder1);folder.remove(folder1);file1.remove(file1);//成功刪除:學習質料//無法刪除: '學習質料'不存在://無法刪除: 'Node.js'不存在:folder.scan(); //這裡相當於執行了一個宏命令//開始掃描根目錄: 目錄//開始掃描'目錄': javascript//javascript: qq.jpg

以上所述是小編給大家介紹的JavaScript組合模式,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對雲棲社區網站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.