Observer mode (publish subscribe mode)

Define the Subject Subject

class Subject {
    constructor() {
        this.state = 0
        this.observers = []
    }
    getState() {
        return this.state
    }
    setState(state) {
        this.state = state
        // When this method is triggered, loop through all observers, notifying each observer that the observation method can be called
    }
    // Add all observers to observers to notify them
    attach(observer) {
        this.observers.push(observer)
    }
}
Copy the code

Define an Observer

class Observer {
    constructor(name, subject) {
        this.name = name
        this.subject = subject
        this.subject.attach(this)},methods() {
        // There are some methods that can be set up for each observer to call to get the different behavior of each observer}}Copy the code

Using an observer

const sub = new Subject()
const observer1 = new Observer('observer1', sub)
const observer2 = new Observer('observer2', sub)
const observer3 = new Observer('observer3', sub)
Copy the code

Decorator mode

Decoration class

function mixins (. list) {
    return function (target) {
        // console.log("list", target)
        Object.assign(target.prototype, ... list) } }const Foo = {
    foo () { alert('foo') }
}

@mixins(Foo)
class MyClass {}Copy the code

Adornment method

function log (target, name, descriptor) {
    var oldValue = descriptor.value;

    descriptor.value = function () {
        console.log(`Calling ${name} with`.arguments);
        return oldValue.apply(this.arguments);
    };

    return descriptor;
}
class Math {
    @log
    add (a, b) {
        returna + b; }}Copy the code

Core-decorators state pattern library