Here are some of the more common design patterns:
- The factory pattern
- The singleton pattern
- The proxy pattern
- Observer model
- The strategy pattern
- The module pattern
- Constructor pattern
- Mixed mode
Details can go to my blog HZCann’s blog if you can click a star⭐ thank you!!
I. Factory model
Factory pattern is one of the most common design patterns used to create objects. It does not expose the concrete logic of creating objects, but encapsulates the logic in a function, which can be regarded as a factory. Factory pattern can be divided into: Simple factories, factory methods, and abstract factories. Here’s a simple example of how simple factories and factory methods can be used in JavaScript:
1. Simple factory
The simple factory pattern is also called the static factory pattern. A factory object decides to create instances of a product object class, which is used to create objects of the same class
For example, in real projects, we often need to render different pages according to the user’s permissions. Some pages owned by the user with advanced permissions are not viewable by the user with lower permissions, so we can save the page that can be seen by the user with different permissions in the constructor.
Let UserFactory = function(role){function SuperAdmin(){this.name =' SuperAdmin ', this.viewPage =[' home ',' user ',' order ',' application ', } function Admin(){this.name =' Admin ', } function Normaluser(){this.name =' normal ', this.viewPage=[' home ', this.viewPage=[' home ', this.viewPage=[' home ', this.viewPage=[' home ', this.viewPage=[' home ', this.viewPage=[' home ', this. } switch (role){case 'superAdmin': return new superAdmin (); break; case 'admin': return new Admin(); break; case 'user': return new Normaluser(); break; // let superAdmin = UserFactory('superAdmin'); // Let superAdmin = UserFactory('superAdmin'); let admin = UserFactory('admin') let normalUser= UserFactory('user')Copy the code
Conclusion:In the example above, UserFactory is a simple factory with three constructors for different users. When we call the factory function, we only need to pass one of the three optional arguments superAdmin, admin, and user to get the corresponding instance objectTo put it simply: you carry your girlfriend to raise 🐟, only you want her to see, she will see, DDDD old cheat playing with women’s feelings of men of course I am very special feeling 🐺 digs the topic we continue <( ̄)  ̄). [GO!] )
Advantages: The advantage of a simple factory is that you only need a correct parameter to get the object you need, without knowing the details of its creation;
Disadvantages: Contains all the objects created within the function logic (constructor) and judge logic code, each adding new constructor also need to modify the judgment logic code, our object instead of the above three 30 or more, this function will be a huge super function, and difficult to maintain, simple plant can only be applied to create a number of objects is less, Used when the creation logic of the object is not complex.
2. Factory method
The factory method pattern is intended to defer the actual creation of the object to the subclass, so that the core class becomes an abstract class. However, it is difficult to implement the creation of abstract classes in JavaScript in the traditional object-oriented way, so in JavaScript we just refer to the core idea of the factory method. We can think of a factory method as a factory class that instantiates an object
For example, in the example above, if we use the factory method, we can write it like this, the factory method we just think of it as a factory that instantiates objects, it only does one thing: instantiate objects, we create objects in safe mode
Summary: In the simple factory, if we add a new user type, we need to change the code in two places, one is to add a new user constructor, one is to add a new user judgment in the logical judgment, while in the abstract factory method, we just need to add userFactory. prototype.
2. Singleton mode(Safe one p🐺)
Definition: guarantees that a class has only one instance and provides a global access point to access it.
Requirements: There are some objects that we usually only need one, such as thread pool, global cache, window object in browser, login float window, etc.
Implementation: A variable identifies whether an object has been created for a class and, if so, returns the previously created object the next time an instance of the class is fetched.
Advantages:
- It can be used to partition namespaces and reduce the number of global variables
- Can be instantiated, instantiated once, instantiated again to produce the first instance
For example, in JS, we can use closures to create and implement this pattern:
Summary: In the above code, we can use single.getInstance to get the example and get the same singleton every time we call it.
In our normal development, we often use this model, such as when we click the login button, the page will appear a login box, and the floating window is the only, no matter how many times you click the login button, the floating window can only be created once, so the login window is suitable to use the singleton pattern.
3. Agency mode(Quick one p🐺)
Proxy mode mainly provides a proxy for other objects to control access to this object, mainly to solve the problems caused by direct access to objects.
For example, to access the object on the remote machine, in object-oriented systems, some object for some reason (such as the object creation overhead is very large, or some operations require safety control, or need to access) outside the process, will have direct access to caused a lot of trouble for the user or the system structure, during a visit to this object we can add an object to this access layer.
In its most basic form, the proxy pattern controls access, and a proxy object implements the same interface as another object (ontology).
Actually work or ontology in do, it is responsible for performing tasks assigned by the object or class, proxy objects do nothing more than temperance access to ontology, agent will not be in another object on the basis of adding methods or modify its method, also won’t simplify the object interface, it realizes the interface and ontology are exactly the same, All method calls made to it are passed to the ontology.
Summary: In the code above, Proxy controls access to an actual proxied object. In the proxy pattern, a common one is the virtual proxy, which is used to control access to ontologies that are expensive to create, delaying instantiation of ontologies until methods are called.
For example, assuming that the instantiation of the PublicLibrary is slow and cannot be completed immediately when a web page loads, we can create a virtual proxy for it and let it postpone the instantiation of the PublicLibrary until necessary. For example, we can use a virtual proxy for lazy loading of images that we often use in the front end. (To put it simply: La Shi does not bring paper, and other people run errands for you and deliver paper to you. La Shi is your behavior and requires your participation. You are the initiator, and your partner is honored to be your agent of La Shi. Slang 🤣 🤣)
4. Observer mode
If you have studied vUE and React frameworks, you will be familiar with the Observer mode. Many MVVM frameworks use the idea of the observer mode, also known as published-subscribe mode.
It defines a one-to-many dependency between objects, when an object’s state is changed, all depend on its object will be notified and update, the observer pattern provides a subscription model, in which objects to subscribe to events and be notified when happen, this model is a cornerstone event-driven programming, it advantageous beneficial good object-oriented design
Definition: A one-to-many dependency between objects.
Requirement: All dependent objects are notified when the state of an object changes.
Advantages: decoupling in time, decoupling between objects.
Implementation:
- Specify who will act as publisher;
- Add a cache list for publishers to store callback functions to notify subscribers;
- When a message is published, the publisher iterates through the cache list, triggering the subscriber callbacks it holds in turn.
For example, if we bind an event to a DOM node in a page, it can be regarded as an observer mode:
Conclusion: In the example above, we need to listen for the user to click on Document. body, but there is no way to predict when the user will click, so we subscribe to the Document. body click event. When the body node is clicked, The body node publishes a “Hello World” message to the subscriber.
5. Strategic mode(Slang said not understand their own understanding SAO years)
The strategy pattern refers to defining a series of algorithms and encapsulating them one by one. The purpose is to separate the use of algorithms from the implementation of algorithms, avoid multiple judgment conditions, and have more expansibility.
Now there is an event in the supermarket, and VIP customers get 50% discount, regular customers get 30% discount, and ordinary customers do not get any discount. Calculate the final amount to be paid. If the strategy mode is not used, our code may be the same as the following:
In the above code, we need a lot of judgments, and if there are a lot of preferences, we need to add a lot of judgments. This violates the open and close principle of the six principles of design patterns. If we use the policy pattern, our code can be written like this:
Summary: In the above code, through the strategy mode, make the customer discount and algorithm decoupling, and make the modification and expansion can be carried out independently, does not affect the use of the client or other algorithms.
When we have multiple judgment branches in our code, and each conditional branch causes the specific behavior of the “class” to change in different ways, we can use policy patterns to improve the quality of our code and make it better for unit testing.
6. Module mode
The module pattern can specify the properties and methods that the class wants to expose without contaminating the world. In the form of closure, the implementation is as follows:
var Person = (function() {
var name = 'xxx'
function sayName() {
console.log(name)
}
return{
name: name,
sayName: sayName
}
})()
Copy the code
Constructor mode and hybrid mode
Constructors and hybrid modes are the two implementations of JS inheritance. The former defines classes in the form of constructors, and the new adds instances. A subclass is an instance of the superclass stereotype.
Refer to the article: www.jianshu.com/p/4f3014fb8…