Home Web Front-end JS Tutorial JavaScript design patterns factory pattern and constructor pattern_javascript skills

JavaScript design patterns factory pattern and constructor pattern_javascript skills

May 16, 2016 pm 04:14 PM
javascript Factory pattern Design Patterns

What is a pattern

I was preparing for the final exam a while ago. It was so tiring and tiring, and I really didn’t have time to update the article. Today I will talk to you about the design patterns in JavaScript.

First of all, what we need to know is: a pattern is a reusable solution, while an anti-pattern is a poor solution to a certain problem.

Common examples of js anti-patterns

1. Pass strings to setTimeout and setInterval instead of functions, which triggers the internal use of eval().
2. Define a large number of variables in the global context to pollute the global namespace
3. Modify the prototype of the Object class
4. Use js in inline form. The js code embedded in the HTML file cannot be included in external unit testing tools.
5. Abusing document.write. If document.write is executed after the page is loaded, it will rewrite the page we are on. If you can use document.creatElement instead, try not to use document.write.

Categories of design patterns

Creative Design Pattern

Creative design patterns focus on handling object creation mechanisms to create objects in a way that is appropriate for a given situation. Properties that fall into this category include:

Constructor, Factory, Abstract, Prototype, Singleton and Builder

Structural Design Pattern

Structural patterns are about object composition and can often be used to find simple ways to establish relationships between different objects.
Patterns that fall into this category include:

Decorator, Facade appearance, Flyweight, Adapter adapter and Proxy agent

Behavioral Design Patterns

Behavioral patterns focus on improving or simplifying communication between different objects in the system.

Behavior patterns include:

Iterator, Mediator, Observer and Visitor

Factory mode

In order to solve the problem of multiple similar object declarations, we can use a method called factory pattern. This method is to solve the problem of a large number of duplications when instantiating objects.

Copy code The code is as follows:


Classification of Factory Pattern

Factory mode is divided into simple factory, abstract factory and smart factory. Factory mode does not require the use of a constructor explicitly.

Simple Factory Pattern: Use a class (usually a singleton) to generate instances.
Complex factory pattern: Use subclasses to determine which specific class instance a member variable should be.

Benefits of Factory Model

The main benefit is that you can eliminate the coupling between objects by using engineering methods instead of the new keyword. Prevent code duplication by centralizing all instantiation code in one location.
Disadvantages of factory model

For most classes, it is best to use the new keyword and constructor, which can make the code simpler and easier to read. Rather than having to look at the factory method to find out. 
The factory pattern solves the problem of repeated instantiation, but there is another problem, that is, the problem of identification, because it is impossible to figure out which object they are instances of.

Copy code The code is as follows:

alert(typeof test1); //Object
alert(test1 instanceof Object); //true

When to use factory pattern?

Factory mode is mainly used in the following scenarios:

1. When objects or components involve high complexity
2. When you need to easily generate different instances of an object according to different environments
3. When dealing with many small objects or components that share the same properties

Constructor pattern

Constructor (constructor method) can be used in ECMAScript to create specific objects. This mode can just solve the problem that the above factory mode cannot identify object instances.

Copy code The code is as follows:


Using the constructor method not only solves the problem of repeated instantiation, but also solves the problem of object recognition. The difference between this mode and the factory mode is:

1. The constructor method does not create an object explicitly (new Object());
2. Directly assign properties and methods to this object;
3. There is no renturn statement.

There are some specifications for constructor methods:

1. The function name and the instantiation constructor name are the same and capitalized (PS: It is not mandatory, but writing this way helps distinguish the constructor from the ordinary function);
2. To create an object through a constructor, you must use the new operator.
Since objects can be created through constructors, where does this object come from, and where is new Object() executed? The execution process is as follows:

1. When a constructor is used and new constructor() is used, new Object() is executed in the background;
2. Give the scope of the constructor to the new object (that is, the object created by new Object()), and this in the function body represents the object created by new Object().
3. Execute the code within the constructor;
4. Return the new object (return directly in the background).

Constructor with prototype

There is an attribute called prototype in js. After calling the js constructor to create an object, the new object will have all the properties of the constructor prototype. In this way, multiple Car objects can be created and have access to the same prototype.

Copy code The code is as follows:



Now a single instance of run() can be shared among all Car objects.
Statement of this Website
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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the application scenarios of factory pattern in java framework? What are the application scenarios of factory pattern in java framework? Jun 01, 2024 pm 04:06 PM

The factory pattern is used to decouple the creation process of objects and encapsulate them in factory classes to decouple them from concrete classes. In the Java framework, the factory pattern is used to: Create complex objects (such as beans in Spring) Provide object isolation, enhance testability and maintainability Support extensions, increase support for new object types by adding new factory classes

The difference between design patterns and architectural patterns in Java framework The difference between design patterns and architectural patterns in Java framework Jun 02, 2024 pm 12:59 PM

In the Java framework, the difference between design patterns and architectural patterns is that design patterns define abstract solutions to common problems in software design, focusing on the interaction between classes and objects, such as factory patterns. Architectural patterns define the relationship between system structures and modules, focusing on the organization and interaction of system components, such as layered architecture.

The wonderful use of the adapter pattern in Java design patterns The wonderful use of the adapter pattern in Java design patterns May 09, 2024 pm 12:54 PM

The Adapter pattern is a structural design pattern that allows incompatible objects to work together. It converts one interface into another so that the objects can interact smoothly. The object adapter implements the adapter pattern by creating an adapter object containing the adapted object and implementing the target interface. In a practical case, through the adapter mode, the client (such as MediaPlayer) can play advanced format media (such as VLC), although it itself only supports ordinary media formats (such as MP3).

Analysis of the Decorator Pattern in Java Design Patterns Analysis of the Decorator Pattern in Java Design Patterns May 09, 2024 pm 03:12 PM

The decorator pattern is a structural design pattern that allows dynamic addition of object functionality without modifying the original class. It is implemented through the collaboration of abstract components, concrete components, abstract decorators and concrete decorators, and can flexibly expand class functions to meet changing needs. In this example, milk and mocha decorators are added to Espresso for a total price of $2.29, demonstrating the power of the decorator pattern in dynamically modifying the behavior of objects.

PHP design pattern practical case analysis PHP design pattern practical case analysis May 08, 2024 am 08:09 AM

1. Factory pattern: Separate object creation and business logic, and create objects of specified types through factory classes. 2. Observer pattern: allows subject objects to notify observer objects of their state changes, achieving loose coupling and observer pattern.

PHP Design Patterns: Test Driven Development in Practice PHP Design Patterns: Test Driven Development in Practice Jun 03, 2024 pm 02:14 PM

TDD is used to write high-quality PHP code. The steps include: writing test cases, describing the expected functionality and making them fail. Write code so that only the test cases pass without excessive optimization or detailed design. After the test cases pass, optimize and refactor the code to improve readability, maintainability, and scalability.

How design patterns deal with code maintenance challenges How design patterns deal with code maintenance challenges May 09, 2024 pm 12:45 PM

Design patterns solve code maintenance challenges by providing reusable and extensible solutions: Observer Pattern: Allows objects to subscribe to events and receive notifications when they occur. Factory Pattern: Provides a centralized way to create objects without relying on concrete classes. Singleton pattern: ensures that a class has only one instance, which is used to create globally accessible objects.

What are the advantages and disadvantages of using design patterns in java framework? What are the advantages and disadvantages of using design patterns in java framework? Jun 01, 2024 pm 02:13 PM

The advantages of using design patterns in Java frameworks include: enhanced code readability, maintainability, and scalability. Disadvantages include complexity, performance overhead, and steep learning curve due to overuse. Practical case: Proxy mode is used to lazy load objects. Use design patterns wisely to take advantage of their advantages and minimize their disadvantages.

See all articles