设计模式 | 青训营笔记

90 阅读1分钟

设计模式->软件开发中可重用的解决一些特定问题的方法,举例:

1、单例模式 Singleton pattern - ensures that only one instance of an object is created, and provides a global point of access to it.确保只有一个实例被创建且提供全局访问。

const Singleton = (function() {
  let instance;

  function createInstance() {
    const object = new Object({ name: "John" });
    return object;
  }

  return {
    getInstance: function() {
      if (!instance) {
        instance = createInstance();
      }
      return instance;
    }
  };
})();

const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();

console.log(instance1 === instance2); // true
console.log(instance1.name); // John
console.log(instance2.name); // John

2、工厂模式 Factory pattern - creates objects without specifying the exact class of object that will be created. 不用特别说明对象所属的类型,对象就能被创建出来

class Car {
  constructor(model, year) {
    this.model = model;
    this.year = year;
  }
}

class CarFactory {
  static createCar(model, year) {
    return new Car(model, year);
  }
}

const car1 = CarFactory.createCar("BMW", 2022);
const car2 = CarFactory.createCar("Audi", 2023);

console.log(car1.model); // BMW
console.log(car1.year); // 2022
console.log(car2.model); // Audi
console.log(car2.year); // 2023

3、观察者模式:Observer pattern allows an object (subject) to notify other objects (observers) automatically when it changes state. 允许某个对象自动观察到其他对象状态的改变

class Subject { // being observed for changes
  constructor() {
    this.observers = [];
  }

  subscribe(observer) {
    this.observers.push(observer);
  }

  unsubscribe(observer) {
    this.observers = this.observers.filter(obs => obs !== observer);
  }

  notify() { // 通知
    this.observers.forEach(observer => observer.update());
  }
}

class Observer {
  constructor(subject) {
    this.subject = subject;
    this.subject.subscribe(this);
  }

  // 一旦观察的对象改变了,自己就会更新自己的状态(调用自己的update方法)
  update() {
    console.log("State changed!");
  }

  unsubscribe() {
    // this -> this observer
    this.subject.unsubscribe(this);
  }
}

const subject = new Subject();
const observer1 = new Observer(subject);
const observer2 = new Observer(subject);

subject.notify(); // State changed! * 2

observer1.unsubscribe();

subject.notify(); // State changed! * 1

我之前写的:

// fn: callback functions
// 允许多个回调函数注册在同一个事件上
class Emitter {
  constructor() {
    this.events = new Map();
  }

  subscribe(eventName, fn) {
    if (!this.events.has(eventName)) {
      this.events.set(eventName, [fn]);
    } else {
      this.events.get(eventName).push(fn);
    }
    const subscription = {
      fn: fn,
      eventName: eventName,
      state: true,
      emit: (...args) => {
        if (subscription.eventName === eventName && subscription.state) {
          subscription.fn(...args);
        }
      },
      unsubscribe: () => {
        subscription.state = false;
      },
    };
    return subscription;
  }
}


///////////gpt update version////////////////
class Emitter {
  constructor() {
    this.events = new Map();
  }

  subscribe(eventName, fn) {
    if (!this.events.has(eventName)) {
      this.events.set(eventName, [fn]);
    } else {
      this.events.get(eventName).push(fn);
    }

    return {
      fn: fn,
      eventName: eventName,
      state: true,
      emit: (...args) => {
        if (this.events.has(eventName) && this.state) {
          this.events.get(eventName).forEach((fn) => {
            fn(...args);
          });
        }
      },
      unsubscribe: () => {
        const fns = this.events.get(eventName);
        if (fns) {
          const index = fns.indexOf(fn);
          if (index !== -1) {
            fns.splice(index, 1);
          }
          if (fns.length === 0) {
            this.events.delete(eventName);
          }
        }
        this.state = false;
      }
    }
  }
}