9、JS常用设计模式

28 阅读1分钟

1. 单例模式(Singleton Pattern)

实际场景:  管理应用程序中的全局配置或状态,例如应用的配置管理器。

代码示例:  应用配置管理器

class AppConfig {
  constructor() {
    if (AppConfig.instance) {
      return AppConfig.instance;
    }
    this.config = {};
    AppConfig.instance = this;
  }

  setConfig(key, value) {
    this.config[key] = value;
  }

  getConfig(key) {
    return this.config[key];
  }
}

// 使用单例模式
const configManager = new AppConfig();
configManager.setConfig('apiUrl', 'https://api.example.com');

const anotherConfigManager = new AppConfig();
console.log(anotherConfigManager.getConfig('apiUrl')); // "https://api.example.com"

2. 观察者模式(Observer Pattern)

实际场景:  实现事件系统,比如页面组件间的事件通知。

代码示例:  简单的事件管理器

class EventEmitter {
  constructor() {
    this.events = {};
  }

  on(event, listener) {
    if (!this.events[event]) {
      this.events[event] = [];
    }
    this.events[event].push(listener);
  }

  emit(event, data) {
    if (this.events[event]) {
      this.events[event].forEach(listener => listener(data));
    }
  }
}

// 创建一个事件管理器实例
const eventEmitter = new EventEmitter();

// 订阅事件
eventEmitter.on('dataReceived', data => {
  console.log(`Data received: ${data}`);
});

// 发布事件
eventEmitter.emit('dataReceived', 'Server data');

3. 策略模式(Strategy Pattern)

实际场景:  表单验证模块,不同的表单字段可以有不同的验证策略。

代码示例:  表单验证

class Validator {
  constructor(strategy) {
    this.strategy = strategy;
  }

  validate(value) {
    return this.strategy(value);
  }
}

// 定义不同的验证策略
const emailValidator = value => /\S+@\S+.\S+/.test(value);
const phoneValidator = value => /^\d{10}$/.test(value);

// 使用策略模式进行验证
const emailCheck = new Validator(emailValidator);
console.log(emailCheck.validate('test@example.com')); // true

const phoneCheck = new Validator(phoneValidator);
console.log(phoneCheck.validate('1234567890')); // true

4. 适配器模式(Adapter Pattern)

实际场景:  适配不同的接口风格,例如使用新的API接口时适配旧有的代码。

代码示例:  API适配器

class OldAPI {
  getData() {
    return 'old data';
  }
}

class NewAPI {
  fetchData() {
    return { data: 'new data' };
  }
}

// 创建一个适配器类,使得新API看起来像旧API
class APIAdapter {
  constructor(newAPI) {
    this.newAPI = newAPI;
  }

  getData() {
    const response = this.newAPI.fetchData();
    return response.data;
  }
}

// 使用新API,通过适配器调用
const newAPI = new NewAPI();
const adaptedAPI = new APIAdapter(newAPI);
console.log(adaptedAPI.getData()); // "new data"

5. 装饰者模式(Decorator Pattern)

实际场景:  动态为对象添加功能,比如在渲染时为组件添加额外的样式或功能。

代码示例:  装饰者添加样式

// 组件基础类
class Component {
  render() {
    return 'Component';
  }
}

// 装饰器类:添加红色样式
class RedBorderDecorator {
  constructor(component) {
    this.component = component;
  }

  render() {
    return `<div style="border: 1px solid red;">${this.component.render()}</div>`;
  }
}

// 装饰器类:添加背景色
class BackgroundDecorator {
  constructor(component) {
    this.component = component;
  }

  render() {
    return `<div style="background-color: yellow;">${this.component.render()}</div>`;
  }
}

// 使用装饰器模式,动态添加功能
let myComponent = new Component();
console.log(myComponent.render()); // "Component"

myComponent = new RedBorderDecorator(myComponent);
console.log(myComponent.render()); // "<div style="border: 1px solid red;">Component</div>"

myComponent = new BackgroundDecorator(myComponent);
console.log(myComponent.render()); // "<div style="background-color: yellow;"><div style="border: 1px solid red;">Component</div></div>"