Several design patterns I want to share
Current mode: Factory mode, Singleton mode, Adapter mode, Decorator mode, Builder mode
Builder Mode
Introduction: The builder pattern is relatively simple, it belongs to a type of creation pattern.
Vernacular: 4 parts: There is a product, a factory can make products, a designer can direct how many to make, and someone wants to buy products.
Users who buy products do not mind the product manufacturing process, they only need products!
function Cola() { = '50g', = '100g' } function Packing() { // The first method of packaging = function(){ ('Create Coke Celery') } = function() { ('Pour Coke into the bottle') } = function() { var cola = new Cola() = true return cola } = function() { () // Create a skin () // Pour into the bottle //Other steps can be added return () // Completed } } function greenPacking() { //Green-skin Coke packaging method = function(){ ('Create green cola crust') } = function() { ('Pour Coke into green bottle') } = function() { var cola = new Cola() = true return cola } = function() { () // Create a skin () // Pour into the bottle //Other steps can be added return () // Completed } } function Boss() { = function(packType) { const pack = new window[packType] = () //Full product output } = function(packType) { (packType); return } } const boss = new Boss() var UserCola = ('greenPacking') // === true
Don’t want anything else, as long as the Cola is produced in the end, there is sugar and water.
The key is to assume an integrated responsibility in the boss function
For the same boss function, I can get Cola of different styles by replacing the Packing function and packaging method.
By passing different desired parameters to the getCola function, we obtain different final products. Implements pluggable function structure.
Decorator mode
Decorators offer more flexible alternatives than inheritance. Decorators use objects used to wrap the same interface, which not only allows you to add behavior to methods, but also sets the methods to original object calls (such as the decorator's constructor).
The decorator is used to add new functions through the form of an overloaded method. This mode can add its own behavior before or after the decorator to achieve a specific purpose.
benefit:
Decorators are an alternative to achieving inheritance. When the script is running, adding behavior to the subclass affects all instances of the original class, but the decorator does not. Instead it can add new behavior to different objects. Refer to the detailed answers to the front-end handwritten interview questions
function iwatch () { = 100; = function() { () } } = function(part) { this[part].prototype = this; //Point the properties on this object to the prototype of the new object return new this[part]; //Return a new object, without modifying the original object, add the properties of the new object} = function() { = function() { ('network') } } = function() { = function() { ('swim') } } var watch = new iwatch(); (); // 100 watch = ('addNetwork'); // Add new behavior, network()watch = ('addSwim'); // Existingnetworkmethod,There are alsoswimmethod
The proposal to introduce the @decorator modifier in ES7 is to refer to Ruan Yifeng's article.
@testable class MyTestableClass { // ... } function testable(target) { = true; } // true
Can be used directly, decorator behavior
@decorator class A {} // Equivalent toclass A {} A = decorator(A) || A;
Factory model
A factory can produce many different products. The most common factory function is the $() function of jQ. The result of each function is a required product.
function Product(name) { = name; } = function () { ('init'); } = function () { ('go'); } function Factory () { } = function(name) { return new Product(name); } //use let f = new Factory(); let a = ('a'); (); (); ();
Adapter mode
Adapter, converts the interface (method or attribute) of one class (object) into another interface to meet user needs and solves the incompatibility of interfaces between classes (objects) through adapters.
function Person () { } = function() { throw new Error("The method must be rewritten!") } = function() { throw new Error("The method must be rewritten!") } function Dog () { } = function() { throw new Error("The method must be rewritten!") } = function() { throw new Error("The method must be rewritten!") } function PersonA () { (this) } = new Person() = function() { ('Person say') } = function() { ('Person Walk') } function DogBlack () { (this) } = new Dog() = function() { ('Dog Walk') } = function() { ('Dog Shout') } //Now I hope that Dog class can learn Say and take a few more stepsfunction DogSayAdapter (DogClass) { (this) = DogClass } = new Dog() = function() { () } = function() { () () } var personA = new PersonA() var dogBlack = new DogBlack() var dogSay = new DogSayAdapter(dogBlack) () () () () () ()//walk * 2
Adapters are not just functional interfaces, but also adaptations of data formats.
When transferring data from front and back ends, adapter mode is often used, that is, easy-to-understand format data, format functions, etc.
vue's computed computing attribute is also an implementation of the adapter mode
const originData = [ { title: 'title', age: 18, content: ['123',321], callback: function(){ (this) } }, { title: 'title2', age: 1, content: ['1',3], callback: function(){ ('title2') } } ] function dataAdapter(data) { return (item => { return { title: , content: (','), init: } }) } var formatData = dataAdapter(originData)
:The data of the original data does not meet the current requirements. Through the adapter, the data is formatted into the desired format, and there is no change to the original data.
Singleton mode
function Simple (name) { = name } = function() { = 'go' () } //static static method = (function() { var ins return function(name){ if (!ins) { ins = new Simple(name) } return ins } })() let a = ('a') // name: a let b = ('b') // name: a b===a//true
In non-singlear mode, the same new Simple() constructor is not equal.
Only create Simple instances once through closures, and everyone uses one for public use.
Lazy singleton mode
Lazy and lazy loading are similar, lazy loading, or loading it when needed, otherwise it will be loaded too much at a time and frequent operations will affect performance.
Although the above code has methods that can be instantiated when needed, it is still not a good way to implement it.
The lazy loaded part can be extracted.
:
var simple = function(fn) { var instance; return function() { return instance || (instance = (this, arguments)); } }; // Create a mask layervar createMask = function(){ // Create div elements var mask = ('div'); // Set style = 'fixed'; = '0'; ... ... (mask); // Click to hide the mask layer = function(){ = 'none'; } return mask; }; // Create a login windowvar createLogin = function() { // Create div elements var login = ('div'); // Set style = 'fixed'; = '50%'; ... ... = 'login it'; (login); return login; }; ('btn').onclick = function() { var oMask = simple(createMask)(); = 'block'; var oLogin = simple(createLogin)(); = 'block'; }
Summarize
I have learned five common and commonly used design patterns. These are often used. I will continue to learn 18 other design patterns in the future. Some design patterns may not be used in actual code typing. There is no harm in learning them, and they can always be used!
There are countless books about design patterns online, but no matter how many you read, it is better to understand it yourself and use it in practice. Many times, several design patterns are used together. If you don’t write them and understand them yourself, you may not be able to understand the common design patterns. This is a pity. I found that the clean and tidy code cannot be explained where it is good, it just looks comfortable, pleasing to the eyes, and runs fast...
This is the end of this article about the handwritten example of JavaScript design pattern. For more related JS design pattern content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!