Design patterns

Today is the beginning of the design pattern, recorded here for later review.

What are design patterns

A pattern is a reusable solution that can be applied to common problems in software design, and another interpretation is a template for how we solve problems – templates that can be used in many different situations. –w3cschool

Why should I study design patterns

  • Senior engineer interview must test knowledge points
  • Design patterns are the only way to write better code
  • Mastering design patterns makes it easier to read popular framework source code
  • To become a project leader, from zero architectural engineering, design patterns are the cornerstone
  • Don’t be a dick
  • .

I learned the four stages of design patterns

  • Consolidate object-oriented knowledge, ES6 class syntax, encapsulation, inheritance, polymorphism, etc
  • Master design principles
  • Master design patterns
  • Finally, do an exercise case

object-oriented

Learning design patterns, object-oriented is the foundation, so let’s review it first

The difference between object-oriented and functional programming

Data storage mode

  • For object orientation, data is stored in objects’ properties, as well as global variables.
  • For functions, data is stored in various scopes, including the global scope.

Data access mode

How the data is stored determines how the data is accessed.

  • For object orientation, accessing data (other than global variables) requires obtaining a reference to the object and then performing operations (directly accessing — public properties, or calling member functions/methods to access — private properties)
  • For functions, data is accessed directly (by function entry or scope chain lookup)

Class-based object-oriented and prototype-based object-oriented

Class-based object orientation

Class defines all attributes that are used for objects that have a characteristic. A class is an abstract thing, rather than any particular individual of the total objects it describes. An instance, on the other hand, is an instantiation of a class and is a member of it

Object oriented based on prototype

The constructor, instance, and prototype are all objects themselves. Prototype-based languages have the concept of so-called prototype objects from which new objects can derive their original properties.

JavaScript has an interesting __proto__ property for accessing its prototype object, constructors, instances, and prototypes themselves all have __proto__ pointing to the prototype object. And then all the way down the prototype chain is pointing to the Object constructor, but the prototype of Object is null

Add methods through prototypes

Student.prototype.study = function() {
  console.log('I'm learning' + this.subject);
}
Copy the code

Why mount methods to prototypes?

For each instance object, the function body of the method is identical, and the execution result of the method is determined only by the instance object. However, each instance generated needs to generate a method to occupy a portion of memory.

Object orientation prior to ES6

There are two ways to create objects before ES6, each of which has its advantages and disadvantages in specific usage scenarios. Let’s take a look at each of these ways.

  • The first is the way object literals are used
  • The second way is to use constructors

The way object literals are used

We create two student objects, student1 and student2, as object literals.


var student1 = {
  name: 'to be'.age: 22.subject: 'Front-end development'
};

var student2 = {
  name: 'little silly'.age: 22.subject: 'Back-end development'
};
Copy the code

Object literals are handy when creating a single, simple object. However, it also has its disadvantages:

  • When generating multiple instance objects, we need to repeat many properties at a time, which is particularly cumbersome to write.
  • Although both are students’ objects, there is no obvious connection between the two objects.

The way constructors are used

A constructor is simply a function that, when instantiated with new, binds its internal reference to this to the instance object.

Let’s create a Student constructor (constructors are usually distinguished from normal functions by starting with a capital letter).

function Student (name, age, subject) {
  this.name = name;
  this.age = age; 
  this.subject = subject;
  console.log(this);
}
Copy the code

We print the pointer to this in the constructor. Since the constructor is a normal function, we can call Student in the same way that a normal function is called.

Student('to be'.22.'Front-end development'); //window{}
Copy the code

As you can see, when Student is called in the normal way, this points to the window. Now use new to instantiate the constructor, generating an instance object student1.

let student1 = new Student('to be'.22.'Front-end development'); 
//Student {name: "a ", age: 22, subject:" b "}
Copy the code

As you can see, when we use new to generate the instantiation object student1, this no longer points to the window, but to the instance itself.

This is how we generate instance objects using the constructor, and when we generate other instance objects using the Student constructor, we can clearly know the connection between the instance objects.

What did New do?

  • Create a new object
  • Allocates memory and assigns the scope of the constructor to the new object, that is, this refers to the new object
  • Execute the code in the constructor
  • Return a new object

Object orientation in ES6

ES6 provides a class-based syntax. But class is essentially a syntactic sugar provided by ES6, while JavaScript is really an object-oriented language based on prototypes.

ES6 uses classes to create objects

/ / define the class
class Student {
  // constructor
  constructor(name, age, subject) {
    this.name = name;
    this.age = age;
    this.subject = subject;
  }

  // a method in a class
  study(){
    console.log('I'm learning' + this.subject); }}// instantiate the class
let student3 = new Student('small chi'.24.'Front-end development');
student3.study(); // I'm learning front-end development
Copy the code

The above code defines a Student class. You can see that it has a constructor method, which is the constructor, and the this keyword represents the instance object. That is, the Student constructor in ES5 corresponds to the constructor method in the Student class in Es6.

The Student class defines a study method in addition to the constructor method. Do not use commas to separate methods; adding them will cause an error. Furthermore, the methods in the class are all defined on the prototype, which we can verify with the following code.

console.log(student3.__proto__.study === Student.prototype.study); //true
console.log(student3.hasOwnProperty('study')); // false
Copy the code

Student3.__proto__ (student. prototype); student. prototype (student. prototype); student. prototype (student. prototype);

The second line of code verifies that student3 has a study method. The result is false, indicating that student3 does not have a study method.

By mounting the Study method to the Prototype object, all instances can inherit the method, and multiple instances’ methods point to the same memory address.

Instance and class

The difference between instance methods and class methods in javascript

  • Class attributes (static attributes) : Access directly through a class, without declaring an instance of the class
  • Class methods (static methods) : Access directly through a class, without declaring an instance of the class
  • Instance attributes (dynamic attributes) : Cannot be accessed directly through a class, but must be accessed through an instance declared by that class
  • Instance methods (dynamic methods) : Cannot be accessed directly through a class, but must be accessed through an instance declared by that class

Person = function(){
}
Persion.sex = "woman";  / / class attribute
Person.eat= function(){  / / class methodsalert("eat");
}
Person.prototype.age = 10; // Instance properties
Person.prototype.dance = function(){ // Instance methodalert("dance");
}
const person = new Person();
person.age;// Instance properties
person.dance();// Instance method
Person.sex;// Static attributes
Person.eat();// Static method
Copy the code

Instances and classes in ES6

Static properties and instance properties

Static attributes require the static keyword

class Foo {
  static num = 1;
    age = 2
}
const foo = new Foo();
console.log(Foo.num);/ / 1
console.log(foo.num);// undefined
console.log(Foo.age);// undefined
console.log(foo.age);/ / 2
Copy the code

If a static method is called on an instance, an error is thrown indicating that the method does not exist.

Static methods require the static keyword

class Foo {
  static classMethod() {
    return 'hello';
  }
}

Foo.classMethod() // 'hello'

const foo = new Foo();
foo.classMethod()
// TypeError: foo.classMethod is not a function

Copy the code

Static methods can have the same name as non-static methods

If a static method contains the this keyword, this refers to the class, not the instance.

class Foo {
  static bar() {
    this.baz();
  }
  static baz() {
    console.log('hello');
  }
  baz() {
    console.log('world'); }}const foo = new Foo();
Foo.bar() // hello
foo.bar() // world
Copy the code

Static methods of a parent class that can be inherited by subclasses.

class Foo {
  static classMethod() {
    return 'hello'; }}class Bar extends Foo {
}

Bar.classMethod() // 'hello'
Copy the code

Static methods can also be called from super objects

class Foo {
  static classMethod() {
    return 'hello'; }}class Bar extends Foo {
  static classMethod() {
    return super.classMethod() + ', too';
  }
}

Bar.classMethod() // "hello, too"
Copy the code

Encapsulation, inheritance, polymorphism

Object – oriented three features: encapsulation, inheritance, polymorphism

encapsulation

Encapsulation is to hide the details of data operation and expose only the external interface. The external callers do not need and cannot know the details and can only access the object through the exposed interface

class School {
  // constructor: create an object to complete initialization
  constructor(id, name) {
    this.id = id
    this.name = name
  }
  // Instance method
  schoolName() {
    console.log(this.name)
  }
  / / class methods
  static schoolOnly() {
    console.log('I'm a class method that can only be called by the function itself.')}}Copy the code

inheritance

Inheritance means that a subclass inherits its parent class. In addition to having all the characteristics of the parent class, a subclass has some more specific characteristics.

class Student extends School {
  constructor(sId, sName, id, name) {
    super(id, name)
    this.sId = sId
    this.sName = sName
  }
  studentName() {
    console.log(this.sName)
  }
  say() {
    console.log('I am a student')}}Copy the code

polymorphism

Multiple classes generated by inheritance can have different responses to the same method. For example, students and teachers can inherit from schools, but they implement their own SAY methods respectively. For a particular instance, we do not need to know whether it is a student or a teacher. We can call the say method directly, and the program will automatically determine how to execute this method.

class Teacher extends School {
  constructor(tId, tName, id, name) {
    super(id, name)
    this.tId = tId
    this.tName = tName
  }
  TeacherName() {
    console.log(this.tName)
  }
  say() {
    console.log('I am a teacher')}} testslet school = new School(1.'No.1 Primary School')
let student = new Student(10.'Daming'.1.'No.1 Primary School')
let teacher = new Teacher(100.'MrLi'.1.'No.1 Primary School')
console.log(student) //Object Student {id: 1, id: 1, sId: 10, sName: "Daming"}
console.log(teacher) //Object Teacher {id: 1, name: "一 primary school ", tId: 100, tName: "MrLi"}
student.studentName() //Daming
student.schoolName()  // The first primary school
student.say() //I am a student
teacher.say() //I am a teacher
School.schoolOnly() // I am a class method that can only be called by the function itself
Copy the code

Small partners feel helpful to you please like 👍👍 support, feel good to write please pay attention to the column

👉👉 design patterns suitable for front-end personnel