Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand the design pattern of JavaScript

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article shows you how to understand the design pattern of JavaScript, which is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

Today, let's talk about these three design patterns.

Singleton mode / combined mode / observer mode

Singleton mode

What is the singleton mode?

As we all know, a constructor can create an object

We new many constructors to get a lot of objects.

Singleton pattern: when instantiating with a constructor, it is the same object no matter how many times it is instantiated

That is, a constructor can only new one object in its lifetime.

That is, when we use a constructor, and every time new comes out with exactly the same object properties / functions / methods, we design it as a singleton pattern.

Core code

The core code of the singleton pattern is simple.

In fact, it is just to judge whether he has ever had a date with new.

If there is, continue to use the previous object, if not, then give you a new

/ / prepare a constructor / / function Person () {} / to be new in the future / / prepare a singleton mode function / / this singleton mode function to turn Person into a singleton mode / / when you want new Person again in the future, just execute the singleton function function singleton () {

Let instance

If (! instance) {/ / if instance has no content / / come here, prove that instance has no content / / assign him new Person instance = new Person ()

}

/ / always return an instance of the first new Person / / that is, always an instance return instance} const p1 = singleton () const p2 = singleton () console.log (p1 = p2) / / true

Application

Let's simply write a demo with this core code.

/ / the function of this constructor is to create a div and add it to the page function CreateDiv () {

This.div = document.createElement ('div')

Document.body.appendChild (this.div)} CreateDiv.prototype.init = function (text) {

This.div [XSS _ clean] = text} / / prepare to make this CreateDiv singleton mode / / make singleton a closure function const singleton = (function () {)

Let instance

Return function (text) {

If (! instance) {

Instance = new CreateDiv ()

}

Instance.init (text)

Return instance

}}) () singleton ('hello') / / the first time, a new div appears on the page, and the content is hellosingleton (' world') / / the second time, no new div appears, but the original div content becomes world

Combination mode

The combination mode is to combine the startup modes of several constructors together.

Then use a "remote control" to make a unified call.

Class GetHome {

Init () {

Console.log ('home')

}} class OpenComputer {

Init () {

Console.log ('turn on the computer')

}} class PlayGame {

Init () {

Console.log ('play games')

}}

The instantiated objects created by the above constructors all start in the same way.

Then we can write these functions in a combined mode.

And then start it together.

Prepare a constructor for a combined pattern

Class Compose {

Constructor () {

This.compose = []

}

/ / add (task) {the method to add a task

This.compose.push (task)

}

/ / A method execute () {to execute the task

This.compose.forEach (item = > {

Item.init ()

})

}}

Let's use our combined pattern constructor to combine the previous functions.

Const c = new Compose () / / put all the tasks to be completed in the queue c.add (new GetHome ()) c.add (new OpenComputer) c.add (new PlayGame) / / the task queue c.execute () / / will execute the init functions of the three objects sequentially

Observer mode

Observer pattern, often referred to as publish-subscribe pattern or message pattern

The English name is Observer.

Official explanation: when the state of an object changes, all objects that depend on it are notified and updated automatically, solving the functional coupling between the subject object and the observer, that is, the problem of notifying other objects when the state of one object changes.

It sounds confusing, but it's not very difficult.

An example

When you want to go to the bookstore to buy books, but it so happens that the books you want to buy today are gone.

We can't always wait in the bookstore and leave our cell phones to the clerk.

When the book you need arrives, he will call you and let you know. Just go and buy it.

After you have bought it, tell him that I have bought it, so you will not be informed of the book if you come back in the future.

AddEventListener

The above example may not be very clear.

But addEventListener is something we've all used.

This thing is actually a standard observer model.

Btn.addEventListener ('click', function () {

Console.log ('btn was clicked')})

The one above is an invisible observer watching btn's every move.

When the btn is clicked, the corresponding function is executed

We can also bind a few more functions

To put it bluntly: the observer mode is that we implement the function of an addEventListener ourselves.

It's just that addEventListaner only has fixed events and can only bind dom elements.

We can bind an event name and choose the trigger time by ourselves.

Write code

First, let's analyze the function.

We need to have an observer (here abstracted as an object {})

You need to have a property, the box where the message is stored (put all the events you bind in it)

You need an on method to add events

An emit method is required to publish the event (trigger)

You need an off method to cancel the method that has been added

Const observer = {

Message: {}

On: function () {}

Emit: function () {}

Off: function () {}}

We write it in the form of a constructor.

Class Observer {

Constructor () {

This.message = {}

}

On () {}

Emit () {}

Off () {}}

Now, the embryonic form of an observer is coming out.

Then it is OK to perfect the method.

ON

Let's write the ON method first

Add an event

Our on method needs to accept two parameters

Event type

Event handling function

Class Observer {

Constructor () {

This.message = {}

}

On (type, fn) {

/ / check whether the event type if (! this.message [type]) {is set in the message box.

/ / prove that there is no such event type in the message box / / so let's add it directly / / and let its value be an array, and then put the event handler function this.message [type] = [fn] in the array.

} else {

/ / prove that there is this event type in the message box / / then we can directly append the event handler function to the array, this.message.push (fn)

}

}

Emit () {}

Off () {}}

EMIT

Then there is the release event.

That is, let's execute the events that we have already subscribed to.

You also need to accept two parameters.

The type of event to trigger

Parameters passed to the event handler

Class Observer {

Constructor () {

This.message = {}

}

On (type, fn) {

/ / check whether the event type if (! this.message [type]) {is set in the message box.

/ / prove that there is no such event type in the message box / / so let's add it directly / / and let its value be an array, and then put the event handler function this.message [type] = [fn] in the array.

} else {

/ / prove that there is this event type in the message box / / then we can directly append the event handler function to the array, this.message.push (fn)

}

}

Emit (type,... arg) {

/ / determine whether you have subscribed to this event if (! this.message [type]) return before

/ / if so, let's deal with the parameter const event = {

Type: type

Arg: arg | | {}

}

/ / Loop executes all event handlers that subscribe to the current event type, this.message.forEach (item = > {

Item.call (this, event)

})

}

Off () {}}

OFF

Finally, remove the event.

Is to remove the event handlers that have been subscribed to.

You also need to accept two parameters.

The type of event to remove

Event handler to be removed

Class Observer {

Constructor () {

This.message = {}

}

On (type, fn) {

/ / check whether the event type if (! this.message [type]) {is set in the message box.

/ / prove that there is no such event type in the message box / / so let's add it directly / / and let its value be an array, and then put the event handler function this.message [type] = [fn] in the array.

} else {

/ / prove that there is this event type in the message box / / then we can directly append the event handler function to the array, this.message.push (fn)

}

}

Emit (type,... arg) {

/ / determine whether you have subscribed to this event if (! this.message [type]) return before

/ / if so, let's deal with the parameter const event = {

Type: type

Arg: arg | | {}

}

/ / Loop executes all event handlers that subscribe to the current event type, this.message.forEach (item = > {

Item.call (this, event)

})

}

Off (type, fn) {

/ / determine whether you have subscribed to this event if (! this.message [type]) return before

/ / if so, we will remove for (let I = 0; I)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report