你不会还不知道JavaScript常用的8大设计模式?

Posted on 2023-04-07 16:14  书中枫叶  阅读(93)  评论(0编辑  收藏  举报

JavaScript 常用的8大设计模式有

  1. 工厂模式:工厂模式是一种创建对象的模式,可以通过一个共同的接口创建不同类型的对象,隐藏了对象的创建过程。
  2. 单例模式:单例模式是一种只允许实例化一次的对象模式,可以通过一个全局访问点来访问它。
  3. 建造者模式:建造者模式是一种创建复杂对象的模式,通过将对象的构建过程分解为多个步骤,逐步构建对象。
  4. 适配器模式:适配器模式是一种将不兼容的接口转换为兼容接口的模式,通过适配器可以使得不同的对象能够相互协作。
  5. 观察者模式:观察者模式是一种定义一对多的依赖关系,当一个对象发生改变时,所有依赖于它的对象都会得到通知并自动更新的模式。
  6. 装饰者模式:装饰者模式是一种在不改变对象自身的基础上,动态地扩展对象的功能的模式,通过装饰器可以给对象添加新的功能。
  7. 策略模式:策略模式是一种定义一系列算法,并将其封装在独立的策略类中,使得它们可以相互替换的模式,通过策略模式可以动态改变对象的行为。
  8. 命令模式:命令模式是一种将请求封装成对象,从而使得请求可以被保存、传递、取消、排队或记录的模式,通过命令模式可以将发出请求的对象和执行请求的对象解耦。

JavaScript 设计模式的示例代码:

  1. 工厂模式:
// 定义一个工厂函数
function createPerson(name, age) {
  const person = {};
  person.name = name;
  person.age = age;
  person.sayName = function() {
    console.log(this.name);
  };
  return person;
}

// 使用工厂函数创建对象
const person1 = createPerson('Alice', 20);
const person2 = createPerson('Bob', 30);

person1.sayName(); // Alice
person2.sayName(); // Bob

  1. 单例模式:
// 定义一个单例对象
const logger = {
  log: function(message) {
    console.log(message);
  }
};

// 使用单例对象记录日志
logger.log('This is a log message.');

3.建造者模式:

// 定义一个建造者类
class PersonBuilder {
  constructor() {
    this.person = {};
  }
  setName(name) {
    this.person.name = name;
    return this;
  }
  setAge(age) {
    this.person.age = age;
    return this;
  }
  build() {
    return this.person;
  }
}

// 使用建造者创建对象
const personBuilder = new PersonBuilder();
const person = personBuilder.setName('Alice').setAge(20).build();
console.log(person); // { name: 'Alice', age: 20 }

  1. 适配器模式:
// 定义一个不兼容的接口
class IncompatibleApi {
  fetchData() {
    console.log('Fetching data from the incompatible API.');
  }
}

// 定义一个适配器类,将不兼容的接口转换为兼容接口
class Adapter {
  constructor(incompatibleApi) {
    this.incompatibleApi = incompatibleApi;
  }
  fetch() {
    this.incompatibleApi.fetchData();
  }
}

// 使用适配器调用兼容接口
const incompatibleApi = new IncompatibleApi();
const adapter = new Adapter(incompatibleApi);
adapter.fetch(); // Fetching data from the incompatible API.

  1. 观察者模式:
// 定义一个主题对象
class Subject {
  constructor() {
    this.observers = [];
  }
  addObserver(observer) {
    this.observers.push(observer);
  }
  removeObserver(observer) {
    const index = this.observers.indexOf(observer);
    if (index !== -1) {
      this.observers.splice(index, 1);
    }
  }
  notify(data) {
    this.observers.forEach(observer => {
      observer.update(data);
    });
  }
}

// 定义一个观察者对象
class Observer {
  constructor(name) {
    this.name = name;
  }
  update(data) {
    console.log(`${this.name} received data: ${data}`);
  }
}

// 使用主题对象通知观察者对象
const subject = new Subject();
const observer1 = new Observer('Alice');
const observer2 = new Observer('Bob');
subject.addObserver(observer1);
subject.addObserver(observer2);
subject.notify('Hello world!'); // Alice received data: Hello world! Bob received data: Hello world!

  1. 装饰者模式:
// 定义一个被装饰的对象
class Component {
  operation() {
    console.log('Component)
    }
}
// 定义一个装饰器类,增强被装饰的对象
class Decorator {
   constructor(component) {
      this.component = component;
   }
operation() {
    this.component.operation();
    console.log('Decorator added new behavior.');
   }
}

// 使用装饰器增强被装饰的对象
const component = new Component();
const decorator = new Decorator(component);
decorator.operation(); // Component, Decorator added new behavior.

  1. 命令模式

在命令模式中,有四个主要的角色:

  1. 命令(Command):封装了请求的所有信息,包括命令的接收者、具体的操作方法等。通常定义一个接口或抽象类,由具体命令类实现。
  2. 具体命令(Concrete Command):实现了命令接口或抽象类,并封装了接收者的操作方法。当接收者需要执行命令时,就调用具体命令的execute()方法。
  3. 调用者(Invoker):负责将命令对象传递给接收者,并在需要时调用命令的execute()方法。调用者不需要知道具体的命令,只需要知道如何调用命令对象。
  4. 接收者(Receiver):具体执行命令的对象。当命令对象的execute()方法被调用时,接收者就会执行相应的操作。
// 定义命令接口
class Command {
  execute() {}
}

// 定义具体命令类
class ConcreteCommand extends Command {
  constructor(receiver) {
    super();
    this.receiver = receiver;
  }

  execute() {
    this.receiver.action();
  }
}

// 定义接收者
class Receiver {
  action() {
    console.log("接收者执行操作。");
  }
}

// 定义调用者
class Invoker {
  setCommand(command) {
    this.command = command;
  }

  executeCommand() {
    this.command.execute();
  }
}

// 创建接收者、命令和调用者对象
const receiver = new Receiver();
const command = new ConcreteCommand(receiver);
const invoker = new Invoker();

// 将命令传递给调用者,并执行命令
invoker.setCommand(command);
invoker.executeCommand(); // 输出:接收者执行操作。

以上是一些常见的 JavaScript 设计模式示例代码。这些示例代码只是用来说明设计模式的基本思想和实现方式,实际应用中可能需要更多的定制和细节处理。

Copyright © 2024 书中枫叶
Powered by .NET 8.0 on Kubernetes