search
HomeWeb Front-endJS TutorialJavaScript design pattern composition pattern analysis_js object-oriented

How to say it? ! Just like an animal (combined object), when it gives birth to offspring (leaf objects), its offspring will have a certain function (for example: digging holes, hearing well, etc.); also like a tree, it There is a root (the composite object) and then there are other branches that grow outward from the tree (the composite object) and leaves that grow outward from those branches (the leaf object). In other words, when an ancestor already exists, then as long as other children derived from this ancestor (including other combined objects under this ancestor) already have a certain function, it looks a bit like inheritance. "Composition pattern" has two types of objects in the hierarchy of composite objects: leaf objects and composite objects. The combined pattern is good at operating on large numbers of objects.
"Composition mode" means that when working on a project, we need to define all the methods that will appear in the project in the composition object (including methods in leaf objects), and their leaf objects will inherit the composition object. When the composite object is instantiated, the methods of its leaf objects are instantiated accordingly. Maybe what I said is a bit confusing, let me use an example to illustrate.
"Composition Mode" is a mode tailored for creating dynamic user interfaces on the web. Using this pattern, you can trigger complex or recursive behavior on multiple objects with a single command.
Using the "combined mode" can bring us two major benefits:
1. A collection of objects and specific sub-objects can be processed in the same way.
2. It can be used to organize a batch of sub-objects into a tree structure, and the entire tree can be traversed.
The combination mode is suitable only if the following two conditions are met at the same time:
1. There is a batch of objects organized into a certain hierarchical system (the specific structure may not be known during development).
2. I hope to perform an operation on this batch of objects or part of them.
Let’s take a look at an example:
The specific requirement is to make a photo gallery and be able to selectively hide or show specific parts of the photo gallery. This may be a single image or a gallery of images. Now two classes are needed to complete this function: the composite object class used as a picture library and the leaf object class used for the picture itself. The code is as follows:
In the above code, the first thing defined is the composite object class and leaf The interface that the object class should implement. In addition to the conventional combination of vision and penny, these types of operations only include hide and show. Next we define the leaf objects. The leaf object implements hide and show. The code is as follows:

Copy the code The code is as follows:

var Composite = new Interface('Composite', ['add', 'remove', 'getChild']); // Check the methods that the composite object Composite should have
var GalleryItem = new Interface( 'GalleryItem', ['hide', 'show']); // Check the methods that the combined object GalleryItem should have
// DynamicGallery Class
var DynamicGallery = function(id){ // Implement Composite, GalleryItem combination Object class
this.children = [];

this.element = document.createElement('div');
this.element.id = id;
this.element.className = 'dynamic-gallery';
}
DynamicGallery.prototype = {
// Implement the Composite composite object interface
add: function(child){
Interface.ensureImplements(child, Composite, DynamicGallery);
this.children.push(child);
this.element.appendChild(child.getElement());
},
remove : function(child){
for (var node, i = 0; node = this.getChild(i); i ){
                                                                                                                                                       
        }
                                                                                                                                                            
},
// Implement the DynamicGallery composite object interface
hide : function(){
} for(var node, i = 0; node = this.getChild(i); i ){
              node.hide(); = 'block';
for(var node, i = 0; node = getChild(i); i ){
node.show();
}
},
// Helper method
getElement : function(){
return this.element;
}
}


The following are the corresponding methods for setting leaf objects:




Copy code


The code is as follows:

// GalleryImage class
var GalleryImage = function(src){          Implement the methods defined in the Composite and GalleryItem combination objects
this.element = document.createElement('img'); this.element.className = 'gallery-image'; this.element.src = src; } GalleryImage.prototype = { // Implement Composite interface
// These are leaf nodes, so we don’t need to implement these methods, we just need to define them
add : function(){},
remove : function(){},
getChild : function(){},
// Implement GalleryItem interface
hide : function(){
this.element.style.display = 'none';
},
show : function(){
this.element.style.display = '';
},
// Helper method
getElement: function(){
return this.element;
}
}


This is an example demonstrating how the combined mode works. Each class is very simple, but thanks to such a hierarchy we can perform some complex operations. The constructor of the GalleryImage class creates an image element. The rest of the class definition consists of the empty composite object method (since this is a leaf node) and the operations required by GalleryItem. Now we can use these two classes to manage images:
Copy code The code is as follows:

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 DyamicGallery('vacation-photos');
for(var i = 0, i vacationPhotos.add(new GalleryImage('/img/vac/image-' i '.jpg'));
}
topGallery.add(vacationPhotos);
topGallery.show();
vacationPhotos.hide();

The advantages of combination mode, using combination mode, simple operations can also produce complex result. Instead of writing glue code that manually traverses arrays or other data structures, you can simply perform an operation on the top-most object and pass the operation to each child object itself. This is especially useful for operations that are performed over and over again. In the Composite pattern, the coupling between individual objects is very loose. Whenever an operation is performed on the top-level composite object, a try-first search is performed throughout the structure to find the node.
The disadvantage of the combined mode is that any operation called on the combined mode will be carried out to all its sub-objects. If this hierarchy is large, the performance of the system will be affected.
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
如何在PHP后端功能开发中合理应用设计模式?如何在PHP后端功能开发中合理应用设计模式?Aug 07, 2023 am 10:34 AM

如何在PHP后端功能开发中合理应用设计模式?设计模式是一种经过实践证明的解决特定问题的方案模板,可以用于构建可复用的代码,在开发过程中提高可维护性和可扩展性。在PHP后端功能开发中,合理应用设计模式可以帮助我们更好地组织和管理代码,提高代码质量和开发效率。本文将介绍常用的设计模式,并给出相应的PHP代码示例。单例模式(Singleton)单例模式适用于需要保

如何通过编写代码来学习和运用 PHP8 的设计模式如何通过编写代码来学习和运用 PHP8 的设计模式Sep 12, 2023 pm 02:42 PM

如何通过编写代码来学习和运用PHP8的设计模式设计模式是软件开发中常用的解决问题的方法论,它可以提高代码的可扩展性、可维护性和重用性。而PHP8作为最新版的PHP语言,也引入了许多新特性和改进,提供更多的工具和功能来支持设计模式的实现。本文将介绍一些常见的设计模式,并通过编写代码来演示在PHP8中如何运用这些设计模式。让我们开始吧!一、单例模式(Sing

深入聊聊设计模式利器之“职责链模式”(附go实现流程)深入聊聊设计模式利器之“职责链模式”(附go实现流程)Jan 17, 2023 am 11:43 AM

本篇文章给大家带来了关于golang设计模式的相关知识,其中主要介绍了职责链模式是什么及其作用价值,还有职责链Go代码的具体实现方法,下面一起来看一下,希望对需要的朋友有所帮助。

Go语言中的ETL的设计模式Go语言中的ETL的设计模式Jun 01, 2023 pm 09:01 PM

随着数据的增长和复杂性的不断提升,ETL(Extract、Transform、Load)已成为数据处理中的重要环节。而Go语言作为一门高效、轻量的编程语言,越来越受到人们的热捧。本文将介绍Go语言中常用的ETL设计模式,以帮助读者更好地进行数据处理。一、Extractor设计模式Extractor是指从源数据中提取数据的组件,常见的有文件读取、数据库读取、A

深入解析Go语言中的单例模式深入解析Go语言中的单例模式Mar 21, 2023 pm 06:36 PM

单例模式是一种常见的设计模式,它在系统中仅允许创建一个实例来控制对某些资源的访问。在 Go 语言中,实现单例模式有多种方式,本篇文章将带你深入掌握 Go 语言中的单例模式实现。

了解JavaScript中的设计模式和最佳实践了解JavaScript中的设计模式和最佳实践Nov 03, 2023 am 08:58 AM

随着JavaScript的不断发展和应用范围的扩大,越来越多的开发人员开始意识到设计模式和最佳实践的重要性。设计模式是一种被证明在某些情况下有用的软件设计解决方案。而最佳实践则是指在编程过程中,我们可以应用的一些最佳的规范和方法。在本文中,我们将探讨JavaScript中的设计模式和最佳实践,并提供一些具体的代码示例。让我们开始吧!一、JavaScript中

设计模式的六大原则是什么设计模式的六大原则是什么Jan 06, 2023 pm 04:25 PM

设计模式的六大原则:1、单一职责原则,其核心就是控制类的粒度大小、将对象解耦、提高其内聚性;2、开闭原则,可以通过“抽象约束、封装变化”来实现;3、里氏替换原则,主要阐述了有关继承的一些原则;4、依赖倒置原则,降低了客户与实现模块之间的耦合;5、接口隔离原则,是为了约束接口、降低类对接口的依赖性;6、迪米特法则,要求限制软件实体之间通信的宽度和深度。

探索Java开发中的设计模式经验与建议探索Java开发中的设计模式经验与建议Nov 22, 2023 pm 04:08 PM

探索Java开发中的设计模式经验与建议设计模式是软件开发中用于解决特定问题的一种面向对象的可复用解决方案。在Java开发中,设计模式是很重要的一部分,它能够提高代码的可读性和可维护性,并且能够加速开发过程。通过运用设计模式,开发人员可以更好地组织和管理代码,同时也能够避免一些常见的开发错误。在Java开发中,有很多常用的设计模式,如单例模式、工厂模式、观察者

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor