5种常用的JavaScript设计模式

433 阅读2分钟

JavaScript设计模式

1.模块模式

模块模式(Module Pattern):模块模式是一种创建可重用组件的方式。它使用匿名函数来创建一个作用域,将私有变量和方法隐藏在这个作用域内部,并返回一个公共接口,使得外部代码可以访问这个模块。

const myModule = (function() {
  let privateVar = 0;
  const privateMethod = function() {
    console.log("private method");
  };

  return {
    publicVar: "public var",
    publicMethod: function() {
      console.log("public method");
      privateVar++;
      privateMethod();
    }
  };
})();

console.log(myModule.publicVar);
myModule.publicMethod();

2. 构造函数模式

构造函数模式(Constructor Pattern):构造函数模式是一种创建对象的方式。它使用函数作为构造函数,并通过new操作符来创建新的对象。构造函数内部使用this关键字来指向新创建的对象,从而将属性和方法添加到对象中

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.introduce = function() {
  console.log(`Hi, my name is ${this.name} and I'm ${this.age} years old.`);
};

const john = new Person("John", 30);
john.introduce();

3.工厂模式

工厂模式(Factory Pattern):工厂模式是一种创建对象的方式。它使用一个工厂函数来创建新的对象,并返回这个对象。工厂函数内部使用类似于构造函数的逻辑来创建新的对象,但不使用new操作符

function createPerson(name, age) {
  return {
    name,
    age,
    introduce: function() {
      console.log(`Hi, my name is ${this.name} and I'm ${this.age} years old.`);
    }
  };
}

const john = createPerson("John", 30);
john.introduce();

4.观察者模式

观察者模式(Observer Pattern):观察者模式是一种将对象之间的一对多关系封装起来的方式。它定义了一种依赖关系,使得当一个对象发生变化时,所有依赖于它的对象都会收到通知

class Subject {
  constructor() {
    this.observers = [];
  }

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

  detach(observer) {
    const index = this.observers.indexOf(observer);
    if (index > -1) {
      this.observers.splice(index, 1);
    }
  }

  notify() {
    for (const observer of this.observers) {
      observer.update(this);
    }
  }
}

class Observer {
  constructor(name) {
    this.name = name;
  }

  update(subject) {
    console.log(`${this.name} received notification from ${subject}`);
  }
}

const subject = new Subject();
const observer1 = new Observer("Observer 1");
const observer2 = new Observer("Observer 2");

subject.attach(observer1);
subject.attach(observer2);

subject.notify();

5.单例模式

单例模式(Singleton Pattern):单例模式是一种保证一个类只有一个实例的方式。它使用一个静态变量来存储实例,并通过一个静态方法来返回这个实例

const singleton = (function() {
  let instance;

  function createInstance() {
    return {
      name: "singleton instance"
    };
  }

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

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

console.log(instance1 === instance2);