返回

模块模式

前端

JavaScript 设计模式浅析:初学者指南

随着 JavaScript 的不断普及,设计模式越来越受到重视。设计模式提供了一种通用且可重用的解决方案,有助于创建灵活、可维护且可扩展的代码。对于刚接触设计模式的初学者来说,掌握以下几种常见模式至关重要。

模块模式是一种封装代码并创建私有变量和函数的方法。它通过将代码包含在一个匿名函数的立即调用函数表达式(IIFE)中实现。例如:

const module = (function() {
  const privateVar = 10;
  const publicVar = 20;

  function privateMethod() {
    console.log("私有方法");
  }

  function publicMethod() {
    console.log("公共方法");
  }

  return {
    publicVar,
    publicMethod
  };
})();

module.publicMethod(); // 输出: 公共方法
module.privateVar; // 输出: undefined

单例模式确保类只有一个实例,并且可以通过全局访问点访问它。例如:

class Singleton {
  static instance = null;

  constructor() {
    if (!Singleton.instance) {
      Singleton.instance = this;
    }

    return Singleton.instance;
  }
}

const singleton1 = new Singleton();
const singleton2 = new Singleton();

console.log(singleton1 === singleton2); // 输出: true

工厂模式提供了一种创建对象的接口,而无需指定具体的类。它允许你创建不同类型的对象,而无需编写复杂的条件语句。例如:

class ShapeFactory {
  createShape(type) {
    switch (type) {
      case "square":
        return new Square();
      case "circle":
        return new Circle();
      default:
        throw new Error("Invalid shape type");
    }
  }
}

class Square {
  draw() {
    console.log("绘制一个正方形");
  }
}

class Circle {
  draw() {
    console.log("绘制一个圆形");
  }
}

const factory = new ShapeFactory();
const square = factory.createShape("square");
const circle = factory.createShape("circle");

square.draw(); // 输出: 绘制一个正方形
circle.draw(); // 输出: 绘制一个圆形

装饰者模式动态地将行为添加到对象。它允许你扩展现有类的功能,而无需修改其源代码。例如:

class Beverage {
  getDescription() {
    return "饮料";
  }
}

class CondimentDecorator extends Beverage {
  constructor(beverage) {
    super();
    this.beverage = beverage;
  }

  getDescription() {
    return this.beverage.getDescription();
  }
}

class Milk extends CondimentDecorator {
  getDescription() {
    return super.getDescription() + ", 加牛奶";
  }
}

class Soy extends CondimentDecorator {
  getDescription() {
    return super.getDescription() + ", 加豆奶";
  }
}

const beverage = new Beverage();
const beverageWithMilk = new Milk(beverage);
const beverageWithSoy = new Soy(beverageWithMilk);

console.log(beverageWithSoy.getDescription()); // 输出: 饮料, 加牛奶, 加豆奶