返回

js常见设计模式:JavaScript常见设计模式实战解析

来源:网络   作者:   日期:2025-11-15 07:39:58  

JavaScript作为一门灵活且强大的编程语言,其设计模式的应用在前端开发中尤为广泛,设计模式是解决特定问题的编程思想,它们并非银弹,但能帮助开发者写出更清晰、可维护的代码,本文将介绍JavaScript中常见的设计模式,包括它们的实现方式、适用场景及优缺点。


单例模式(Singleton Pattern)

定义:确保一个类只有一个实例,并提供一个全局访问点。

实现方式

const Singleton = (() => {
  let instance;
  function createInstance() {
    return new SomeClass();
  }
  return {
    getInstance: () => {
      if (!instance) {
        instance = createInstance();
      }
      return instance;
    }
  };
})();

适用场景:配置管理、全局缓存、数据库连接池等。

优点:控制资源、避免重复创建对象。

缺点:过度使用可能导致代码难以测试。


工厂模式(Factory Pattern)

定义:根据输入参数的不同,返回不同类型的对象。

实现方式

class CarFactory {
  static createCar(type) {
    switch (type) {
      case 'sedan': return new Sedan();
      case 'suv': return new SUV();
      default: throw new Error('Invalid car type');
    }
  }
}

适用场景:对象创建逻辑复杂时。

优点:解耦对象创建与使用。

缺点:过度使用可能增加代码复杂度。


代理模式(Proxy Pattern)

定义:为对象提供一个代理,并在访问对象时执行控制。

实现方式

const realSubject = new RealSubject();
const proxy = new Proxy(realSubject);
proxy.request(); // 代理逻辑

适用场景:延迟加载、访问控制、日志记录。

优点:增强对象功能而不改变原类。

缺点:可能引入性能开销。

js常见设计模式:JavaScript常见设计模式实战解析


观察者模式(Observer Pattern)

定义:定义对象间的一对多依赖关系,当一个对象改变状态时,所有依赖者会收到通知。

实现方式

class Subject {
  constructor() {
    this.observers = [];
  }
  subscribe(fn) { this.observers.push(fn); }
  unsubscribe(fn) { this.observers = this.observers.filter(f => f !== fn); }
  notify(data) { this.observers.forEach(fn => fn(data)); }
}
// 使用示例
const subject = new Subject();
subject.subscribe(data => console.log(data));
subject.notify('Hello');

适用场景:事件处理、状态同步。

优点:解耦发布者与订阅者。

缺点:可能导致内存泄漏(未正确管理订阅)。


组合模式(Composite Pattern)

定义:将对象组合成树形结构,以实现部分-整体层次。

实现方式

class Component {
  add(component) { throw new Error('Method not implemented'); }
  remove(component) { throw new Error('Method not implemented'); }
  getChild(index) { throw new Error('Method not implemented'); }
  operation() { throw new Error('Method not implemented'); }
}
class Leaf extends Component {
  operation() { return 'Leaf'; }
}
class Composite extends Component {
  components = [];
  add(component) { this.components.push(component); }
  operation() { return this.components.map(c => c.operation()).join(' | '); }
}

适用场景:文件系统、UI组件树。

优点:统一处理叶子节点和组合节点。

缺点:递归结构可能复杂。


装饰者模式(Decorator Pattern)

定义:动态地给对象添加功能,而不修改原类。

js常见设计模式:JavaScript常见设计模式实战解析

实现方式

class Component { operation() { return 'Component'; } }
class Decorator extends Component {
  constructor(component) { super(); this.component = component; }
  operation() { return `Decorator(${super.operation()})`; }
}

适用场景:权限控制、日志记录。

优点:避免继承的滥用。

缺点:过度装饰可能导致代码难以维护。


策略模式(Strategy Pattern)

定义:定义一系列算法,封装它们并使它们可互换。

实现方式

class Context {
  constructor(strategy) { this.strategy = strategy; }
  execute() { return this.strategy.algorithm(); }
}
const strategyA = { algorithm() { return 'Strategy A'; } };
const context = new Context(strategyA);
console.log(context.execute());

适用场景:排序算法、支付方式选择。

优点:算法解耦,易于扩展。

缺点:可能增加类的数量。


适配器模式(Adapter Pattern)

定义:将一个接口转成另一个接口,使原本不兼容的类可以一起工作。

实现方式

js常见设计模式:JavaScript常见设计模式实战解析

class Adaptee { specificRequest() { return 'Adaptee'; } }
class Target {
  request() { return 'Target'; }
}
class Adapter extends Adaptee {
  request() { return `Adapter(${this.adapteeRequest()})`; }
}

适用场景:集成第三方库、旧系统兼容。

优点:复用现有类,增强灵活性。

缺点:可能引入不必要的复杂性。


命令模式(Command Pattern)

定义:将请求封装为对象,以便存储、传递、调度或队列化请求。

实现方式

class Command {
  execute() { throw new Error('Method not implemented'); }
}
class LightOn extends Command {
  execute() { console.log('Light on'); }
}
class Invoker {
  command;
  setCommand(c) { this.command = c; }
  executeCommand() { this.command.execute(); }
}

适用场景:宏命令、事务操作。

优点:解耦请求发送者与接收者。

缺点:命令对象可能过多。


模板方法模式(Template Method Pattern)

定义:定义算法框架,允许子类重写步骤。

实现方式

class AbstractClass {
  templateMethod() {
    this.primitiveOperation();
    this.requiredOperations();
  }
  primitiveOperation() { }
  requiredOperations() { throw new Error('Method not implemented'); }
}
class ConcreteClass extends AbstractClass {
  primitiveOperation() { console.log('Concrete operation'); }
  requiredOperations() { console.log('Required operation'); }
}

适用场景:框架设计、业务流程管理。

优点:代码复用,扩展灵活。

缺点:子类可能破坏框架结构。


设计模式是JavaScript开发中的重要工具,它们帮助开发者写出更优雅、可维护的代码,理解这些模式的核心思想并灵活运用,是成为一名优秀前端工程师的关键,设计模式并非万能,过度使用可能导致代码复杂化,在实际开发中,应根据具体需求选择合适的设计模式,并保持代码的简洁性。

分类:编程
责任编辑:今题网
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。

文章已关闭评论!