JavaScript 设计模式是提高代码可维护性和可扩展性的关键。下面是一些常用的 JavaScript 设计模式,帮助你更好地理解和应用它们。

单例模式 (Singleton)

单例模式确保一个类只有一个实例,并提供一个全局访问点。

class Database {
  constructor() {
    if (!Database.instance) {
      Database.instance = this;
    }
    return Database.instance;
  }
}

const db = new Database();
const anotherDb = new Database();
console.log(db === anotherDb); // true

观察者模式 (Observer)

观察者模式定义对象间的一对多依赖关系,当一个对象改变状态时,所有依赖于它的对象都会得到通知并自动更新。

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

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

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

class Observer {
  update() {
    console.log('Observer notified!');
  }
}

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

subject.subscribe(observer1);
subject.subscribe(observer2);

subject.notify(); // Observer notified!

工厂模式 (Factory)

工厂模式定义一个用于创建对象的接口,让子类决定实例化哪一个类。

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

  bark() {
    console.log('Woof!');
  }
}

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

  meow() {
    console.log('Meow!');
  }
}

class AnimalFactory {
  createAnimal(type) {
    if (type === 'dog') {
      return new Dog('Buddy');
    } else if (type === 'cat') {
      return new Cat('Kitty');
    }
  }
}

const factory = new AnimalFactory();
const dog = factory.createAnimal('dog');
dog.bark(); // Woof!

const cat = factory.createAnimal('cat');
cat.meow(); // Meow!

装饰者模式 (Decorator)

装饰者模式动态地给一个对象添加一些额外的职责,而不改变其接口。

class Button {
  constructor() {
    this.label = 'Click me!';
  }

  click() {
    console.log('Button clicked!');
  }
}

class ButtonWithCounter extends Button {
  constructor() {
    super();
    this.clickCount = 0;
  }

  click() {
    this.clickCount++;
    super.click();
    console.log(`Button clicked ${this.clickCount} times.`);
  }
}

const button = new ButtonWithCounter();
button.click(); // Button clicked!
button.click(); // Button clicked!
button.click(); // Button clicked!

模板方法模式 (Template Method)

模板方法模式定义一个算法的骨架,将一些步骤延迟到子类中。

class Coffee {
  brew() {
    console.log('Brewing coffee...');
  }

  addMilk() {
    console.log('Adding milk...');
  }

  addSugar() {
    console.log('Adding sugar...');
  }
}

class CoffeeWithMilk extends Coffee {
  addMilk() {
    console.log('Adding milk with foam...');
  }
}

const coffee = new Coffee();
coffee.brew();
coffee.addMilk();
coffee.addSugar();

const coffeeWithMilk = new CoffeeWithMilk();
coffeeWithMilk.brew();
coffeeWithMilk.addMilk();
coffeeWithMilk.addSugar();

更多关于 JavaScript 设计模式的内容,请访问我们的 JavaScript 设计模式教程