Learn about JavaScript design pattern (P1)

Tram Ho

The Design Pattern concept is so familiar to programmers, the article will learn about some design patterns and implement them in javascript.

1. Constructor pattern

This is the pattern used when instantiating objects in javascript along with the methods and properties. This is not a strange pattern because it is used quite a lot. Let’s look at an example

2. Factory pattern

Factory pattern is another pattern used to initialize. In the example below we will create a factory class BallFactory which will have a method that accepts params, depending on these params, the object upon initialization will correspond to the class.

3. Prototype pattern

In this pattern, we will use an existing object to create a new object. This pattern is very useful in javascript because it leverages prototype inheritance instead of class inheritance. Let’s look at an example below

4. Singleton pattern

This pattern is also very commonly used to initialize objects. For example

5. Adapter pattern

This pattern is often used when trying to create an “intermediate adapter” to connect the new refactor code and the old code, so that it can be used normally. For example

6. Decorator pattern

This pattern is used when adding behaviors or functions to a class. For example

Above are the common patterns used in javascript when initializing objects in javascript. Hope the article is helpful to everyone

Reference

https://www.toptal.com/javascript/comprehensive-guide-javascript-design-patterns https://addyosmani.com/resources/essentialjsdesignpatterns/book/ https://medium.com/better-programming/javascript-design -patterns-25f0faaaa15

Share the news now

Source : Viblo