HLJ 发布于
2025-05-22 15:56:18
1阅读

前端工程师必知:15个JavaScript高级设计模式实战解析

以下是前端工程师需要掌握的 15 个 JavaScript 高级设计模式实战解析,结合现代开发场景和 ES6+ 特性:


一、模块模式 (Module Pattern)

场景:封装私有变量 + 公共 API 暴露

const Counter = (() => {
  let count = 0; // 私有变量

  return {
    increment: () => ++count,
    getCount: () => count
  };
})();

Counter.increment();
console.log(Counter.getCount()); // 1

应用:工具库封装、避免全局污染


二、代理模式 (Proxy Pattern)

场景:API 请求缓存拦截

const apiProxy = new Proxy(realApi, {
  get(target, endpoint) {
    const cache = new Map();
    return async (...args) => {
      const key = `${endpoint}_${JSON.stringify(args)}`;
      if (cache.has(key)) return cache.get(key);
      const result = await target[endpoint](...args);
      cache.set(key, result);
      return result;
    };
  }
});

优势:透明化缓存逻辑,降低主业务耦合


三、观察者模式 (Observer Pattern)

场景:实现自定义事件系统

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

  on(event, listener) {
    const listeners = this.events.get(event) || new Set();
    listeners.add(listener);
    this.events.set(event, listeners);
  }

  emit(event, ...args) {
    this.events.get(event)?.forEach(fn => fn(...args));
  }
}

// 使用案例:组件间通信

四、装饰器模式 (Decorator Pattern)

场景:React HOC 高阶组件

const withLogger = (WrappedComponent) => {
  return class extends React.Component {
    componentDidMount() {
      console.log(`Component ${WrappedComponent.name} mounted`);
    }
    render() {
      return <WrappedComponent {...this.props} />;
    }
  };
};

五、策略模式 (Strategy Pattern)

场景:表单验证规则切换

const validationStrategies = {
  email: (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value),
  phone: (value) => /^1[3-9]\d{9}$/.test(value)
};

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

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

// 使用
const emailValidator = new FormValidator(validationStrategies.email);

六、组合模式 (Composite Pattern)

场景:树形菜单组件

class MenuComponent {
  constructor(name) {
    this.name = name;
    this.children = [];
  }

  add(component) {
    this.children.push(component);
  }

  render() {
    return `
      <div class="menu-item">
        ${this.name}
        ${this.children.map(child => child.render()).join('')}
      </div>
    `;
  }
}

七、状态模式 (State Pattern)

场景:订单状态机

class Order {
  constructor() {
    this.state = new PendingState();
  }

  nextState() {
    this.state = this.state.next();
  }
}

class ShippedState {
  next() {
    return new DeliveredState();
  }
}

八、工厂模式 (Factory Pattern)

场景:动态创建 UI 组件

class ComponentFactory {
  static create(type) {
    switch(type) {
      case 'button': return new Button();
      case 'input': return new Input();
      default: throw new Error('Invalid component type');
    }
  }
}

九、单例模式 (Singleton Pattern)

场景:全局状态管理

class Store {
  static instance;

  constructor() {
    if (!Store.instance) {
      this.state = {};
      Store.instance = this;
    }
    return Store.instance;
  }
}

const store1 = new Store();
const store2 = new Store();
console.log(store1 === store2); // true

十、适配器模式 (Adapter Pattern)

场景:兼容新旧接口

class LegacyAPI {
  requestLegacy() { /*...*/ }
}

class NewAPIAdapter {
  constructor(legacyApi) {
    this.legacyApi = legacyApi;
  }

  fetch() {
    return this.legacyApi.requestLegacy().then(transformData);
  }
}

十一、备忘录模式 (Memento Pattern)

场景:实现撤销/重做功能

class EditorHistory {
  constructor() {
    this.states = [];
  }

  push(state) {
    this.states.push(JSON.stringify(state));
  }

  pop() {
    return JSON.parse(this.states.pop());
  }
}

十二、职责链模式 (Chain of Responsibility)

场景:中间件管道

const middlewarePipeline = [
  (req, next) => {
    console.log('Middleware 1');
    next();
  },
  (req, next) => {
    console.log('Middleware 2');
    next();
  }
];

function runPipeline(req) {
  let index = 0;
  const next = () => index < middlewarePipeline.length && 
    middlewarePipeline[index++](req, next);
  next();
}

十三、模板方法模式 (Template Method)

场景:算法骨架定义

class DataProcessor {
  process() {
    this.validate();
    this.transform();
    this.save();
  }

  validate() { /* 默认实现 */ }
  abstract transform(); // 需子类实现
  save() { /* 默认实现 */ }
}

十四、享元模式 (Flyweight Pattern)

场景:优化大量相似对象

class IconFactory {
  constructor() {
    this.icons = new Map();
  }

  getIcon(type) {
    if (!this.icons.has(type)) {
      this.icons.set(type, new Icon(type));
    }
    return this.icons.get(type);
  }
}

十五、依赖注入模式 (Dependency Injection)

场景:解耦服务依赖

class AuthService {
  constructor(httpClient, logger) {
    this.http = httpClient;
    this.logger = logger;
  }
}

// 使用容器管理依赖
const container = {
  http: new AxiosClient(),
  logger: new WinstonLogger()
};

const authService = new AuthService(container.http, container.logger);

设计模式选择原则:

  1. KISS 原则:优先简单实现,避免过度设计
  2. 关注点分离:每个模式解决特定问题
  3. 可测试性:模式应用不应阻碍单元测试
  4. 框架适配:结合 React/Vue 等框架特性

掌握这些模式的关键在于理解其适用场景,而非强行套用。建议通过实际项目中的复杂问题来驱动模式的选择和优化。

当前文章内容为原创转载请注明出处:http://www.good1230.com/detail/2025-05-22/737.html
最后生成于 2025-06-05 15:07:00
此内容有帮助 ?
0