返回

js设计模式有哪几种:JavaScript设计模式全解析,从入门到精通

来源:网络   作者:   日期:2025-11-15 07:36:42  

JavaScript作为一门灵活且强大的编程语言,其设计模式在现代开发中扮演着至关重要的角色,无论你是前端开发新手,还是经验丰富的工程师,掌握JavaScript设计模式都能让你的代码更加优雅、可维护和可扩展,本文将带你深入了解JavaScript中最常用的几种设计模式,包括它们的核心思想、应用场景以及代码示例。


什么是设计模式?

设计模式是一套被反复使用的、经过验证的解决方案,用于解决软件设计中的常见问题,它们不是某种可以直接复制的代码,而是一种思维方式,帮助开发者写出更清晰、更健壮的代码。

在JavaScript中,设计模式的应用尤为重要,因为JavaScript是一门灵活的语言,允许多种编程范式(如面向对象、函数式编程等),设计模式可以帮助开发者在复杂项目中保持代码的简洁性和可维护性。


JavaScript设计模式分类

JavaScript中的设计模式可以分为以下几类:

创建型模式

创建型模式关注对象的创建机制,帮助开发者创建对象时保持系统的灵活性和可扩展性。

1 工厂模式(Factory Pattern)

核心思想:通过一个工厂函数来创建对象,避免直接使用new操作符,使代码更加灵活。

代码示例

class User {
  constructor(name, type) {
    this.name = name;
    this.type = type;
  }
}
function createUser(name, type) {
  if (type === 'admin') {
    return new User(name, type);
  } else if (type === 'guest') {
    return new User(name, type);
  }
}
const admin = createUser('Alice', 'admin');
const guest = createUser('Bob', 'guest');

2 抽象工厂模式(Abstract Factory Pattern)

核心思想:提供一个接口,用于创建相关或依赖对象的家族,而无需指定具体类。

js设计模式有哪几种:JavaScript设计模式全解析,从入门到精通

代码示例

class Button {
  render() {
    return 'Button';
  }
}
class WindowsButton extends Button {
  render() {
    return 'Windows Button';
  }
}
class MacButton extends Button {
  render() {
    return 'Mac Button';
  }
}
function createUI(os) {
  if (os === 'windows') {
    return new WindowsButton();
  } else if (os === 'mac') {
    return new MacButton();
  }
}
const ui = createUI('windows');
console.log(ui.render());

结构型模式

结构型模式关注类和对象的组合,使它们能够结构化地形成更大的结构。

1 适配器模式(Adapter Pattern)

核心思想:将一个类的接口转换成客户希望的另一个接口,使得原本不兼容的类可以一起工作。

代码示例

class OldSystem {
  print() {
    console.log('Old System');
  }
}
class NewSystem {
  display() {
    console.log('New System');
  }
}
class Adapter extends OldSystem {
  print() {
    this.display();
  }
}
const oldSystem = new OldSystem();
const adapter = new Adapter();
oldSystem.print(); // Old System
adapter.print();   // New System

2 组合模式(Composite Pattern)

核心思想:将对象组合成树形结构以表示“部分-整体”的层次结构,使得客户端可以统一处理单个对象和组合对象。

代码示例

js设计模式有哪几种:JavaScript设计模式全解析,从入门到精通

class Component {
  render() {
    console.log('Component');
  }
}
class Leaf extends Component {
  render() {
    console.log('Leaf');
  }
}
class Composite extends Component {
  components = [];
  add(component) {
    this.components.push(component);
  }
  render() {
    console.log('Composite');
    this.components.forEach(comp => comp.render());
  }
}
const leaf1 = new Leaf();
const leaf2 = new Leaf();
const composite = new Composite();
composite.add(leaf1);
composite.add(leaf2);
composite.render();

行为型模式

行为型模式关注对象之间的责任分配和通信方式。

1 观察者模式(Observer Pattern)

核心思想:定义对象间的一对多依赖关系,当一个对象状态发生改变时,所有依赖它的对象都会收到通知并自动更新。

代码示例

class Subject {
  constructor() {
    this.observers = [];
  }
  subscribe(observer) {
    this.observers.push(observer);
  }
  unsubscribe(observer) {
    this.observers = this.observers.filter(obs => obs !== observer);
  }
  notify(message) {
    this.observers.forEach(observer => observer.update(message));
  }
}
class Observer {
  update(message) {
    console.log(`Observer received: ${message}`);
  }
}
const subject = new Subject();
const observer1 = new Observer();
const observer2 = new Observer();
subject.subscribe(observer1);
subject.subscribe(observer2);
subject.notify('Hello World!');

2 命令模式(Command Pattern)

核心思想:将请求封装为对象,使得可以独立于请求发送者和接收者来执行请求。

代码示例

class Command {
  execute() {
    // Base implementation
  }
}
class LightOnCommand extends Command {
  execute() {
    console.log('Light is ON');
  }
}
class LightOffCommand extends Command {
  execute() {
    console.log('Light is OFF');
  }
}
class RemoteControl {
  command = null;
  setCommand(command) {
    this.command = command;
  }
  executeCommand() {
    this.command.execute();
  }
}
const remote = new RemoteControl();
const lightOn = new LightOnCommand();
const lightOff = new LightOffCommand();
remote.setCommand(lightOn);
remote.executeCommand(); // Light is ON
remote.setCommand(lightOff);
remote.executeCommand(); // Light is OFF

其他常用设计模式

单例模式(Singleton Pattern)

核心思想:确保某个类只有一个实例,并提供一个全局访问点。

js设计模式有哪几种:JavaScript设计模式全解析,从入门到精通

代码示例

class Singleton {
  static instance = null;
  constructor() {
    if (!Singleton.instance) {
      Singleton.instance = this;
    }
    return Singleton.instance;
  }
  static getInstance() {
    if (!Singleton.instance) {
      Singleton.instance = new Singleton();
    }
    return Singleton.instance;
  }
}
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // true

装饰器模式(Decorator Pattern)

核心思想:动态地给对象添加额外的职责,而不改变原有对象的结构。

代码示例

class Component {
  operation() {
    console.log('Component');
  }
}
class Decorator extends Component {
  component = null;
  constructor(component) {
    super();
    this.component = component;
  }
  operation() {
    this.component.operation();
  }
}
class ConcreteDecorator extends Decorator {
  operation() {
    console.log('Before decoration');
    super.operation();
    console.log('After decoration');
  }
}
const component = new ConcreteDecorator(new Component());
component.operation();

JavaScript设计模式是构建健壮、可维护代码的关键,通过掌握这些设计模式,你可以更好地应对复杂项目中的各种挑战,无论你是初学者还是资深开发者,持续学习和实践设计模式都将提升你的编程能力。

希望本文能帮助你理解JavaScript设计模式的核心概念和应用场景,如果你对某一种模式特别感兴趣,可以进一步深入学习和实践,相信你会有所收获!


参考资源

  • 《JavaScript设计模式》书籍
  • MDN Web 文档
  • 《设计模式:可复用面向对象软件的基础》

如果你有任何问题或想了解更多关于JavaScript设计模式的内容,欢迎在评论区留言!

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

文章已关闭评论!