JavaScript设计模式:组合模式与外观模式解析
1. 组合模式
1.1 组合模式示例
组合模式允许我们将对象组合成树形结构以表示“部分 - 整体”的层次结构。以下是一个使用组合模式组织图片库的示例代码:
var topGallery = new DynamicGallery('top-gallery');
topGallery.add(new GalleryImage('/img/image-1.jpg'));
topGallery.add(new GalleryImage('/img/image-2.jpg'));
topGallery.add(new GalleryImage('/img/image-3.jpg'));
var vacationPhotos = new DynamicGallery('vacation-photos');
for(var i = 0; i < 30; i++) {
vacationPhotos.add(new GalleryImage('/img/vac/image-' + i + '.jpg'));
}
topGallery.add(vacationPhotos);
topGallery.show(); // Show the main gallery,
vacationPhotos.hide(); // but hide the vacation gallery.
通过上述代码,我们可以使用 DynamicGallery 类任意次数地组织图片。由于组合可以嵌套在自身
超级会员免费看
订阅专栏 解锁全文
978

被折叠的 条评论
为什么被折叠?



