(Common front-end design patterns). Many of our interviews require handwritten code, so we try to use ES6 when writing, and use design mode inside. In this way, we can get an excellent grade. If we just write out the function by hand, we can only get a pass (mainly interview and others competition).
Learn about github
Try to talk about design patterns in plain English. It’s not enough to see them once, and it’s not enough to remember them this time. Incorporating design patterns into our code is our goal, and I’m going to talk about some that we use, but we didn’t know they were added to it.
Object-oriented design principles Factory pattern, Abstract Factory pattern State pattern Proxy pattern singleton pattern observer pattern (and subscribe to publish) adapter pattern appearance patternCopy the code
object-oriented
What is object oriented programming (never say “everything is an object” and no more), object oriented is you don’t have to worry about how to use it, you just know how to use it. (Wish you could say it your way, too)
Xiao Hong lives in class 1, class 1 is a whole, there are xiaoxi, Xiaoxi and Xiaoxi in class 1, the school assigned tasks to Class 1 and asked class 1 to do a thorough cleaning on the playground, the class has a thorough cleaning method. Let’s first build a class of this class. We don’t need to pay attention to xiao Hong, Xiao Xi, Xiao Xi, xiao Xi in Class 1. We will go directly to New Class 1 () and then use the current cleaning method.
// Develop good programming habits. (=. =) class 1 class{constructor(){this.小红 = new 小红() this.小红 = new 小红() this. = new brook () this. = new brook ()} Let's go clean up (){... }}let1 class = new 1 class() 1 class. Go cleaning together ()Copy the code
If you still don’t understand, read the following
You want egg fried rice
You take the egg, the rice, the oil and you fry it and you end up with egg fried rice. (Not object-oriented, this is process-oriented.) You go to a restaurant and order scrambled eggs. (This is object oriented, you don't need to pay attention to how the egg fried rice is cooked) (hahahahahahaha 😄) You walk to a building (wow! Steel, cement, wood...) (Facing the process) You walk up to a building (wow! Building) (Object-oriented)Copy the code
Now that you know what object facing is, let’s compare object oriented and procedure oriented
1. Process oriented is actually object oriented at the bottom, but we write the process on the object class, process oriented is used in this way why bad, (advantage is also some good performance, do not have to go to a new instance, reduce the performance overhead) 1. Not easy to maintain (thousands of lines of code are thrown together and known to all who have written) 2. Not easy to extend (thousands of lines of code are thrown together and known to all who have written) 3. Not easy to reuse (thousands of lines of code are together, write all know) 2. Object-oriented Object-oriented has inheritance, encapsulation, polymorphic characteristics, object-oriented advantages are easy to see, 1. Easy maintenance 2. Easy extension 3. Easy reuseCopy the code
Object-oriented inheritance:
Es6 inheritance
class A{
Afun(){
}
}
class B extends A{
}
letB = new b () b.fun () // b can inherit A methodCopy the code
Common common inheritance
Prototype chain inheritancefunction A(){}
A.prototype.Afun = function() {}
function B(){}
B.prototype = new A()
letB = new b () b.fun (); // The prototype can call A method from A. // The prototype can call A method from A. // The constructor of A method can be inherited from Afunction A(a){this.a = a}
A.prototype.Afun = function() {console.log(123)}
function B(){A.call(this,1)}
letB = new b () b.a // can obtain the current // problem, the current does not inherit A method, can only use A method mixfunction A(a){
this.a = a
}
A.prototype.Afun = function() {
console.log('Afun')}function B(){
A.call(this,1)
}
B.prototype = A.prototype
B.prototype.constructor = A
letB = new b () console.log(b.a) b.fun (Copy the code
Object-oriented pair encapsulation (hiding object pair properties and methods, providing properties and usage methods to the outside world) improves reusability and security.
Object oriented js does not provide a template for polymorphism (the ability to have different manifestations of the same behavior)
class A{
toString(){
console.log('A')
}
}
class B extends A{
toString(){
console.log('B')
super.toString();
}
}
class C extends A{
toString(){
console.log('C') super.toString(); }}let b = new B()
b.toString()
let c = new C()
c.toString()
Copy the code
// B and C both inherit from A and both have toString methods (same behavior), but their capabilities (state) are different (can be different ways)Copy the code
Design principles
1. Single responsibility principle (the function of the class should be single, not all functions can be written in the class) 2. Open and closed principle (open for extension, closed for modification, function to function can be extended, but reduce function to modify) 3. 4. Dependency inversion principle (front-end not so good use) 5. Interface separation principle (front-end not how to use, there is no interface) need to understand the design principles behind the baiduCopy the code
Factory pattern, abstract factory pattern
Factory mode, which instantiates different objects by passing in different short parameters. For example: One day you go to a restaurant and want kung pao chicken, and the restaurant instantiates kung pao chicken for you.
Please develop good programming habits. (=. =) class Restaurant{constructor()type){
switch (type) {
case 'Kung Pao Chicken':
returnNew Kung Pao Chicken ()break;
case 'Scrambled eggs with tomatoes':
returnScrambled eggs with New Tomatobreak;
default:
throw "Our restaurant does not have the dish you want sorry, please go out and turn left!!"
break; }}}let mincedChicken= new Restaurant('Kung Pao Chicken')
let scrambledTomato = new Restaurant('Scrambled eggs with tomatoes')
Copy the code
Abstract factory mode is to customize the structure of instances. For example, both kung pao chicken and scrambled egg with tomato can be eaten, so they have the same structure to eat. For example, if a restaurant has the function of cooking, other restaurants can also cook, so the cooking method can be used as an abstract class to restrict instances. Abstract classes (constraints on instances that have the same method (structure)),
Abstract Factory pattern: Factory pattern has multiple (more than one) abstract classes that constrain the current instance (=). = I don’t know if I understand it right. I hope there are big guys who can comment below to teach me.)
// Develop good programming habits. (=. =) class CommercialStreet {constructor(){this. Tomato scrambled egg = new tomato scrambled egg () this. New cream cake () this. Eat () this. Eat ()}} class abstractEat{constructor() {if(new.target===eat){
throw new Error('Abstract classes cannot be instantiated! ')}}eat(){
throw new Error('Abstract methods cannot be called! '}} // Home style cooking class tomato scramble egg extends abstractEat{constructor(){
console.log('Scrambled eggs with tomatoes');
}
eat(){
console.log('Scrambled eggs with tomatoes are delicious.'}}} // class abstract cake extends abstractabstractat {constructor(){
console.log('Cream cake');
}
eat(){
console.log('The cream cake smells good.')}}Copy the code
The factory pattern focuses on the creation of the current product. Advantages: good encapsulation, compliance with the open closed principle. Disadvantages: Increased system complexity abstract Factory pattern focuses on the current abstract class, as well as the current product. Advantages: We don't need to know the specifics of the product, just look at the method (structure) of the current abstract class to programCopy the code
The state pattern
An object has a state change, and every state change triggers a logic. We can’t always if… Else, so we separate the state from the current object, for example, traffic lights are the most common. Red is (stop), yellow is (warning) and green is (go). So we can isolate all three states and methods. Improve code reuse, in line with the open and closed principle
Class RedLamp{constructor(){
this.state = 'red light'
console.log('I'm a red light');
}
handle(){
console.log('Red light stop')
}
}
class GreenLamp{
constructor(){
this.state = 'green light'
console.log('I'm green.');
}
handle(){
console.log('Green go')
}
}
class YellowLamp{
constructor(){
this.state = 'yellow'
console.log('I'm a yellow light');
}
handle(){
console.log('Yellow light Warning')
}
}
class Content{
constructor(){
this.state = null
console.log('I am a substance')} handleState(lamp){this.state = lamp. State // The method that executes the current lamp, lamp.handle()}} entityletCon = new Content() // Red light entityletRed = new RedLamp() // Green entityletGreen = new GreenLamp() // Yellow light entityletYello = new YellowLamp() // Current YellowLamp con.handleState(Red) // yellow light con.handleState(Yello) // Green light con.handleState(Green)Copy the code
Advantages of state mode: in line with the open and closed principle, the code can be maintained. Disadvantages: Many classes are added, each class has its own methods and states, increasing the load of the systemCopy the code
// Pomise = = Any young man in need can have a look... I'll update it later. I'm busy at work today. Tomorrow to the audience elder brother, write more, what front end does not understand the content can @ younger brother message (younger brother will be updated by ability). What special want to know, little brother can also write a few moreCopy the code
The singleton pattern
When we were playing video games, record points were singletons. The singleton mode is the same as the loading mode of the UI component that element writes. Element’s JSX-style components don’t look as good as iViewui, but the code inside the components feels a bit more robust. Your likes and attention are my motivation to write.
Class SingleObject{login(){
console.log('login'Singleobject.getinstance = (singleObject.getInstance = (singleObject.getInstance = (singleObject.getInstance))function() {// Save the current instance with a closurelet instance = null;
return function(params) {
if(! instance){ instance = new SingleObject() }return instance;
}
})()
let SingleObject1 = SingleObject.getInstance()
let SingleObject2 = SingleObject.getInstance()
console.log(SingleObject1===SingleObject2)
Copy the code
// class SingleObject{Instancelogin(){
console.log('login')
}
static getInstance() {if(! this.instance){ this.instance = new SingleObject() }returnthis.instance; }}let SingleObject1 = SingleObject.getInstance()
let SingleObject2 = SingleObject.getInstance()
console.log(SingleObject1===SingleObject2)
Copy the code
Lazy: As with lazy loading, it is necessary to create real examples (this can be used when the instance is complex). Hungry style: Create instances at the beginning of the lifecycle (if the instance is not complex, it will affect page loading speed if it is)Copy the code
Advantages of singleton mode: There is only one instance, which occupies less memory, but improves performance. Disadvantages: less frequent use, poor scalability, and business changes have to be changed.Copy the code
The proxy pattern
The proxy mode is that we do not access the original object directly, but access the original object by accessing the proxy object. For example, if you are a director, you will definitely not contact the star directly, but the star’s agent, who will decide whether the star will cooperate with you.
Class Star{constructor(name){this.name = name}sing(){
console.log('I can sing');
}
}
class Agent{
constructor(){
console.log('I'm an agent.');
}
sing(price,name){
if(price>1000000){
console.log('Our baby has a schedule.');
letDehua = new Star(name) console.log(' I am${name}`)
dehua.sing()
}else{
console.log('I'm sorry we don't have a star available.'); }}}let agent = new Agent()
agent.sing(10000,'Andy Lau') // I am sorry that our star has no schedule.'Andy Lau'(I'm Andy Lau. I can singCopy the code
Observer mode (and subscribe to publish)
Observer mode is for example, you and Xiao Ming both want to drink milk, and then call the milk station. The milk station staff will deliver the goods to you in a unified way, which is the observer mode, while the subscription mode is that you call the milk station agent, instead of directly contacting the milk station, the milk station only needs to deliver the goods to the agent, and you only need to contact the agent. So instead of having to deal with delivery or anything like that, the milk station would be able to subscribe to publish.
Adapter mode
For example, when you go to Work in Europe, you cannot use their socket board directly, so you need to add an adapter outside our charger and then you can use their socket board. The most common adapter mode is that when an old interface and a new interface are used at the same time, the old interface can be called by the adapter. This makes it easier to decouple our code.
The appearance model
The facade pattern is the most common pattern, and we use it the most when we define a bunch of methods that provide a uniform exit. This approach is an appearance pattern. Our front end and back end interaction is a facade, the server has a unified entry point.
The last
See the end 🙏 thank you, more like on github facing ❤️ is the best for me to encourage, I will try to share some of my own experience and the correct way to eat
Seek to rely on the spectrum push (Beijing area) can leave a message I +. =