What are design patterns? What is the difference between design patterns and Javascript?

Tram Ho

Design Patterns

Surely everyone who is reading this article has also sat on the chairs of universities, colleges or through exploration has also heard through design patterns so what is design patterns and what is it useful in the process of broadcasting. software development?

What are patterns and design patterns?

A pattern is a design pattern of events or objects that can be used as a model or model that can be used to solve problems. In software development, a pattern is a solution to a common problem. A pattern is not necessarily a solution that can be normally copied and pasted but an abstraction, a pattern to solve all kinds of problems.

Identifying patterns is important because:

  • They help write better code through but the old experience has come to imagine that we won’t have to reinvent the wheel because in our experiments has shown its effect.
  • Supporting a level of abstraction can thus focus on solving more complex problems without having to worry about low-level details because the patterns have solved that problem.
  • Not only that but they also help improve integration between developers and groups. Simply, if the devs working together understand the technique or approach, it will be easier to develop maintenance later. Usually to get the most general level of development to improve the level of software development we should learn from: Design patterns, Coding patterns, Antipatterns.

Design patterns are patterns originally defined by the book “Gang Gang of Four” (named after the four authors), first published in 1994 with the title “Design Patterns: Elements of Reusable Object -Oriented Software “.

Some design patterns you’ve probably heard of such as singleton, factory, decorator, observer, …

Usually when it comes to Design Patterns, people often think of strong support languages ​​for static-class but have you ever thought of design patterns for javascripts a language based on untyped dynamic prototype?

Coding patterns are actually much more interesting. It is dedicated JavaScript templates related to the unique features of the language, such as the use of various functions.

At first glance Antipatterns has a bit of negative or even annoying sound on its name. An Antipatterns is not the same as an error or coding error. It is only a common approach but it causes more problems than it solves.

But in this article I just focus on Design patterns to give you the most general look.

Singleton

The idea of ​​the singleton pattern is that there is only one instance of a class. This means that the second time you use the same class to create a new object, you’ll get the same object that was created the first time. And how does singleton apply to JavaScript? In JavaScript there is no class, only objects. When you create a new object, there’s really no such object and the object when created is actually a singleton.

In JavaScript, objects are never equal unless they are the same object, so even if you create an identical object with properties, it will not be the same with the first one.

So you can say that every time you create an object using the object, you actually create a singleton without having to use any syntax.

Using new

JavaScript doesn’t have a class, so the verbatim definition for singleton doesn’t make much technical sense. But JavaScript has a new syntax to create objects using constructor functions and sometimes you may want to deploy singleton with this syntax. The idea is that when you use new to create several objects using the same constructor, you will only get new pointers for the same object.

In this example, uni is only created the first time the constructor is called. The second (and third, fourth, etc.) same uni object is returned. This is why uni === uni2, because they are basically two references pointing to the same object. And how to do this in JavaScript?

You need to build the Universe constructor, this object is saved when it is created and then returned a second time when the constructor is called. There are several solutions to this:

  • You can use a global variable to store instances
  • You can store in a static property in the constructor function. Functions in JavaScript are objects, so they can have properties. You could have something like Universe.instance and store the object there. This is a good, neat solution with the only drawback that the instance attribute is publicly accessible and your external code can change it.
  • You can wrap instances in a closure. This keeps the instances private enough and is not accessible outside the constructor function.

Instance in a Static Property

As you can see, this is a simple solution with the only drawback is that the instance is public. It is unlikely that other codes will change it by mistake

Instance in a Closure

Another way to perform singleton like class is to use a closure to protect the single instance. You can do this by using private static members.

The initial constructor is called the first time and it returns this value as usual. Then the second, the third time, etc. The rewritten constructor has access to the instance variable via closure and simply returns it. The restriction is that the rewritten function (in this case, the constructor function of Universe ()) will lose any additional properties between the initial initialization and the initialization.

If the purpose is to point to the original prototype constructor, then just edit a bit:

Factory

The purpose of the factory is to create objects. It is usually implemented in a class or a static method of a class, with the following purposes:

  • Perform repeat operations when setting similar objects.
  • Provides a way to create objects without knowing the exact type (class) through the factory.

The second point that is more important in static class languages, is that it is not necessary to create instances of classes. In JavaScript, this implementation is fairly easy.

Objects created by factory methods (or classes) are inherited by design from the same parent object; They are specific subclasses that perform specialized functions. Sometimes common parents are the same class containing the factory method. Through the example below will help you somewhat understand about the factory:

  • A CarMaker constructor.
  • A static method of CarMaker called Factory (), creates car objects.
  • The dedicated constructors CarMaker.Compact, CarMaker.SUV and CarMaker.Convertible are inherited from CarMaker. They will all be defined as static properties of the parent class so that they can be retrieved.

We will have :

Perhaps var corolla = CarMaker.factory ('Compact') would be the most recognizable in the factory model. You have a method that takes an input parameter as string and returns an object with each type of object without resorting to new constructors. They are actually just a function for creating objects based on a type defined by an input string.

There is no difficulty in implementing the factory model. All you need to do is look for the constructor to create an object for each type of request. In this case, a simple naming convention was used to map object types to their constructors.

Interator

In the iterator pattern, you have an object that contains several types of aggregated data. This data can be stored locally in a complex structure and you want to provide easy access to each component based on that structure. Users don’t need to know how you structure your data. All they want is to get it with individual elements.

In the iterator pattern, your object needs to provide the next () method. Calling next () in the order must return the next row in which it will be up to you to decide what the meaning of the next is in your specific data structure.

Assuming that your object is called agg, you can access each data element by calling next () in a loop like so:

In the pattern, aggregators also usually provide a way to determine if they have reached the end of the data, hasNext ().

Now that we have use cases, let’s look at how to implement such a composite object. When implementing the interator pattern, it is important to store data and pointers (indexes) to the next available element:

To provide additional support for data access you can also add methods like:

  • rewind () : Reset cursor to the original position.
  • current () : Returns the current value of the current cursor.

Strategy

The strategy template allows you to choose algorithms during runtime. Your code may work with the same interface but selected from a number of built-in algorithms to handle their specific task. An example of using a strategy template will solve the form validation problem. You can create a validator object using the validate () method. This method will validate with from and return the same result or an error that cannot be validated. But depending on the specific form and the data to be validated, your validator can choose different types to test and select the most appropriate algorithm to perform. Assume that you have a piece of data and You want to verify if it is valid or not:

In order for the validator to know what is the best strategy to use in this particular example, you need to first configure the validator and set rules about what you consider to be valid and acceptable.

Now the validator object is configured to handle your data, call the validate () method and print any authentication errors on the console:

Now let’s look at the code that executes the validator:

And finally, the main part of the validtor object:

As you can see, the validator object is generic and can be used for all validation use cases. If you want to add some other validate process just define more run configuration and validate () method.

Mediator

A big or small application is made up of separate objects. All of these objects are more or less in line with each other and still maintain the desired maintenance and changes without affecting the rest of the application. As the application grows, you add more objects. Then, during the refactoring process, the objects are removed and reorganized. When objects depend too much on each other through direct communication, this results in unwanted tight links. When objects are tightly coupled, it is not easy to change one object and inevitably affect many others, this case affects the estimation of subsequent tasks. The mediator model alleviates this situation by switching back to weak links for improved maintenance.

Figure 1. Model of components participating in Mediator model.

To get a better idea let’s start with an example of using mediator model. This app will be a game in which two players are given 30 seconds to see who will press the button more times than the other. Player 1 competes by pressing 1 and Player 2 pressing 0. An updated scoreboard with current scores. Participants will be:

  • Player 1
  • Player 2
  • Scoreboard
  • Mediator Mediator knows about all other objects. It communicates with the input device, handles keystroke events, determines which players have their turn and notifications. The Player is only updating its own score and notifying the mediator points that have been made. Mediator updated with transcripts and updated on an intuitive interface. Other than Mediator, in objects do not know anything about any other object. It would be easy to add a new person and update the points for new people.
Figure 2. Model of the game keystrokes.

Player objects are created using the Player () constructor with point and name attributes. The play () method will increase the score and notify the mediator

The scoreboard object has an update () method, called by the mediator after each player’s turn. Rankings do not know about any player and do not store points; It only displays the number of points given by the mediator:

Finally, the mediator object, which initializes the game, creates player objects using the setup () method, and tracks the player via properties. The played () method is called by each player after each turn. The final method is to keypress (), handle keyboard events, determine which players have their turn and notify the player:

And the last thing is to set up and end the game:

Observer

The observer pattern is widely used in client-slide programming in JavaScript. All browser events (hover, keystrokes, etc.) are examples of patterns. Another name for it is also custom events, meaning events that you create with intent, as opposed to events that the browser triggers. Another name is the subscriber / publisher pattern.

The purpose behind this model is to eliminate strong links between objects. Instead of one object calling another object’s method, the object registers for a specific activity and receives events. The subscriber is also called the observer, while the observed object is called the publisher or subject. When the publisher announces an event all subscribers will receive the message as an event object. To understand how this model works, let’s take a look at the specific example that assumes that you have a publisher that will publish daily newspapers and that a subscriber will receive notifications whenever a notification happens every month. . The paper object needs to have one subscribers, an array that stores all subscribers. The registration action is simply added to this array. When an event happens, paper is sent to the list of subscribers and notified them. Notice means calling a method of the subscriber object. So when subscribing to a subscriber, provide one of your methods to the paper’s subscription method. Paper can also unsubscribe with unsubscribe (), which means deleting from subscribers. The final method of paper is also the most important method to publish () which will send notifications to the list of all subscribers.

subscribers An array of subscribers () In addition to the array of subscribers unsubscribe () Deletes the array of subscribers () from the subscribers array and calls the registered method.

All three methods require a type parameter, because the publisher can trigger some events to publish both magazines and newspapers, and subscribers can choose to subscribe to one of them.

Here, an example implementation of the publisher’s function, defining all required members of the visitSubscribers () help method:

And here, a function takes an object and turns it into a publisher by copying the publisher methods:

Now let the person make paper objects. All it can do is publish daily and monthly:

We now have a subscriber, and lie about two methods:

Now Joe will subscribe to the paper:

Now to see the result of using paper to trigger some events

Result:

The good part is that the paper object does not hard code joe and joe does not have a hardcode paper nor does it need a mediator object. The objects involved in the link are weak and do not need much editing, we can add more subscribers to the paper; Joe can also unsubscribe at any time.

summary

Through the article I have introduced over what is pattern?, What is Design Patterns? Design Patterns in javascript an untyped dynamic prototype language is interesting. Finally I introduced how to implement some pretty good patterns in javascript.

Share the news now

Source : Viblo