series

  • Using JavaScript learning design patterns (1) | small volume of free learning
  • Using JavaScript learning design patterns (2) | small volume of free learning
  • Using JavaScript learning design patterns (3) | small volume of free learning
  • Using JavaScript learning design patterns (4) | small volume of free learning

preface

Last year, I first read the performance optimization nuggets pamphlet of Xiu Yan, and gained a lot.

After that, I bought this book of core principles and application practices of JavaScript design patterns, and just happened to have a small volume of free learning activities recently, so I hurried to sort out this note, and supplemented the rest of the design patterns that were not written in the booklet. In order to understand and deepen my impression, I combined the examples of JavaScript writing in the learning process.

It is more like a summary study note than an article.

Why study design patterns?

Before you learn, what are design patterns?

Design Pattern is a series of routines to solve specific problems. It is not a syntax specification, but a set of solutions to improve code reusability, maintainability, readability, robustness, and security.

It is a set of used, widely known, classified code design lessons.

There are recipes for cooking, there are walkthroughs for games, and in every field there are “ways” that we can achieve our goals well and quickly. In the programming world, the “repertoire” of programming is design patterns.

Learning it is also learning the routine of the programming world, on the upgrade of strange dozen equipment has a great help. In the fast-changing world of the front end, design patterns are also “once learned, for life” knowledge.

Principles of design patterns

Describe a recurring problem and the core of the solution to the problem. This way, you can use the solution again and again without having to rework.

One big rule:

  • Demeter’s Law: Also known as the least knowledge law, a software entity should interact with as few other entities as possible, each software unit should have the least knowledge of the other units, and be limited to those software units closely related to its own unit.

Five principles:

  • The single responsibility principle: A class should have only one cause for change, in short, a single function.
  • Open Closed principle: Open for extensions, closed for modifications.
  • Richter’s substitution rule: Where a base class appears, a subclass must appear.
  • Interface isolation principle: an excuse should be a role, should not do things dare to do, should do all. In short, reduce coupling and dependency.
  • The dependency rollover principle: Program for interfaces that rely on abstractions rather than concrete ones.

Common in JavaScript are the single feature and open closed principles.

High cohesion and low coupling

Design patterns help us make our code more reusable, extensible, maintainable, and flexible. Our ultimate goal with design patterns is to achieve high cohesion and low coupling in our code.

To give an example in real life, for example, in a company, each department usually performs its own duties and does not interfere with each other. When each department needs to communicate, special person in charge will be used for docking.

In software, too, a functional module focuses on one function, and a module preferably only implements one function. This is called cohesion.

The interaction between modules and systems is inevitable, but we should try to reduce the case that a single module cannot be used independently or transplanted due to the interaction. As much as possible, separate interfaces are provided for external operations, which is called low coupling

Packaging changes

In real development, code that doesn’t change basically doesn’t exist, so I try to minimize code changes.

The core of a design pattern is to observe the change and immutability in your entire logic and then separate the immutability to make the change flexible and the immutability stable.

Types of design patterns

Commonly used can be divided into three types of creation, structure, behavior, a total of 23 patterns.

Create a type:

  • [x] Factory mode
  • [x] Singleton mode
  • [x] Prototype pattern
  • [x] Constructor schema
  • [x] Abstract factory pattern

Structured:

  • [x] Decorator mode
  • [x] Adapter mode
  • [x] Proxy mode
  • [x] Bridge mode
  • [x] Appearance mode
  • [x] Combination mode
  • [x] Share mode

Behavior type:

  • [x] Iterator mode
  • [x] Publish/subscribe (Observer)
  • [x] Policy mode
  • [x] State mode
  • [x] Interpreter mode
  • [x] Mediator mode
  • [x] Visitor mode
  • [x] Memo mode
  • [x] Template method pattern
  • [x] Chain of responsibility mode
  • [x] Command mode

Create a type

The factory pattern

This type of design pattern is the creation pattern, which provides the best way to create objects.

In factory mode, we create objects without exposing the creation logic to the client, and by using a common interface to point to the newly created objects. In JS, it is implemented with the help of constructors.

example

A class is going to do an entry system, entry a person, you have to write once.

let liMing = {
  name: "Li Ming".age: 20.sex: "Male"};Copy the code

If multiple entries are made, a class can be created.

class Student {
  constructor(name, age, sex) {
    this.name = name;
    this.age = age;
    this.sex = sex; }}let zhangSan = new Student("Zhang".19."Male");
Copy the code

The factory model is to separate the process of creating objects and use it so that only brainless input is needed, just like a factory, as long as enough raw materials are given, it can easily produce finished products.

summary

  • The constructor is separated from the creator, encapsulating the new operation
  • In line with the principle of openness and closure

The singleton pattern

Definition of a singleton pattern: guarantees that a class has only one instance and provides a global variable to access it.

This ensures that a class has only one instance object.

For example, Vuex and jQuery

example

Use scenario: a single object, such as a popover, should only be created once, no matter how many times it is clicked. Implementation is also simple, using a variable cache.

[Click to view Demo] : Singleton mode – online examples

For example, the above bullet frame will be created only when the button is clicked for the first time. After that, the bullet frame will not be created, but will be used before.

In this way, a bullet box applied to the singleton pattern is implemented.

summary

  • Maintains an instance and returns it if it has been created
  • In line with the principle of openness and closure

The prototype pattern

Specify what kind of objects to create with prototype instances, and create new objects by copying these prototypes.

example

In JavaScript, the prototype pattern is implemented in ECMAscript5 with the proposed object. create method, which uses existing objects to provide __proto__ for the created Object.

var prototype = {
  name: "Jack".getName: function() {
    return this.name; }};var obj = Object.create(prototype, {
  job: {
    value: "IT",}});console.log(obj.getName()); // Jack
console.log(obj.job); // IT
console.log(obj.__proto__ === prototype); //true
Copy the code

Where there is a prototype, there is a reason

Constructor pattern

In object-oriented programming languages, a constructor is a special method used in a class to initialize a new object. And can accept methods that parameters can be used to set the properties of the instance object

function Car(model, year, miles) {
  this.model = model;
  this.year = year;
  this.miles = miles;
  // this.info = new CarDetail(model)
  // Attributes can also be generated using new
}

// Override toString on the prototype object
Car.prototype.toString = function() {
  return this.model + " has done " + this.miles + " miles";
};

/ / use:
var civic = new Car("Honda Civic".2009.20000);
var mondeo = new Car("Ford Mondeo".2010.5000);
console.log(civic.toString()); // Honda Civic has done 20000 miles
console.log(mondeo.toString()); // Ford Mondeo has done 5000 miles
Copy the code

The constructor is implemented using inherited properties on the prototype chain.

Abstract Factory pattern

The Abstract Factory pattern uses class abstraction to make the business applicable to the creation of a cluster of product classes, not to instances of a particular class of products.

There is no direct abstract class in JS. Abstract is a reserved word, but not yet implemented, so we need to simulate the abstract class by throwing an error in the method of the class. If the method is not overridden in the inherited subclass, the error will be thrown.

const Car = function() {};
Car.prototype.getPrice = function() {
  return new Error("Abstract methods cannot be called");
};
Copy the code

In object-oriented languages, there is the abstract factory pattern. First, an abstract class is declared as a parent class to generalize the characteristics needed for a product class. The subclasses that inherit this parent class need to implement the methods declared in the parent class to implement the functions declared in the parent class:

/** * The subType class inherits from an abstract class of type superType in the factory class@param SubType The class * to be inherited@param The abstract class type */ in the superType factory class
const VehicleFactory = function(subType, superType) {
  if (typeof VehicleFactory[superType] === "function") {
    function F() {
      this.type = "Vehicle";
    }
    F.prototype = new VehicleFactory[superType]();
    subType.constructor = subType;
    subType.prototype = new F(); Subclass subType needs to inherit not only the stereotype methods of the corresponding superType class, but also its object properties
  } else throw new Error("This abstract class does not exist.");
};
VehicleFactory.Car = function() {
  this.type = "car";
};
VehicleFactory.Car.prototype = {
  getPrice: function() {
    return new Error("Abstract methods not available");
  },
  getSpeed: function() {
    return new Error("Abstract methods not available"); }};const BMW = function(price, speed) {
  this.price = price;
  this.speed = speed;
};
VehicleFactory(BMW, "Car"); // Inherits the Car abstract class
BMW.prototype.getPrice = function() {
  // Override the getPrice method
  console.log(`BWM price is The ${this.price}`);
};
BMW.prototype.getSpeed = function() {
  console.log(`BWM speed is The ${this.speed}`);
};
const baomai5 = new BMW(30.99);
baomai5.getPrice(); // BWM price is 30
baomai5 instanceof VehicleFactory.Car; // true
Copy the code

Abstract factories allow you to create products of a class cluster, and instanceof allows you to check the category of the product and has the necessary methods for that class cluster.

Original from Ninety: links to original blog posts

This article is part of the “Gold Nuggets For Free!” Event, click to view details of the event