JavaScript 设计模式 —— 以及何时真正应该使用它们
I’m happy to translate the article for you, but I need the text you’d like translated. Could you please paste the content (or the portion you want translated) here? I’ll keep the source line and all formatting exactly as you requested.
JavaScript 设计模式 — 前端开发真正重要的东西
JavaScript 应用增长迅速——功能增多、模块增多、复杂度提升。没有结构,即使是资深开发者也会被技术债务淹没。
设计模式帮助你
- ✅ 组织代码
- ✅ 避免重复
- ✅ 提升可维护性
- ✅ 安全扩展功能
- ✅ 构建可预期的架构
并非所有经典设计模式在 JavaScript 中都适用。下面列出的模式是 真正与 JS 相关,并在实际前端项目中得到使用。
1. 单例模式
它是什么
一种确保 只有一个实例 存在的模式。
示例
class AuthService {
constructor() {
if (AuthService.instance) return AuthService.instance;
this.user = null;
AuthService.instance = this;
}
}
何时使用
- 认证管理器
- 主题管理器
- 应用配置
- 全局缓存层
真实案例
你的 React/Angular 应用不应创建多个认证处理器。单例保证用户会话只有唯一的真实来源。
2. 模块模式
它是什么
封装私有逻辑,只暴露需要的部分。
示例
const Cart = (() => {
let items = [];
function add(item) { items.push(item); }
function get() { return items; }
return { add, get };
})();
何时使用
- 实用工具函数
- 数据服务
- 本地存储包装器
- 分析模块
真实案例
storageService 不应暴露内部键名或前缀。模块模式将这些细节设为私有,同时提供干净的公共 API。
3. 观察者模式
它是什么
允许一个对象在状态变化时通知多个监听者。
示例
class Observable {
constructor() { this.subscribers = []; }
subscribe(fn) { this.subscribers.push(fn); }
notify(value) { this.subscribers.forEach(fn => fn(value)); }
}
何时使用
- 事件系统
- UI 更新
- 实时数据流
- 基于发布‑订阅的应用
真实案例
- 原生 JS 中的 UI 状态更新
- 通知中心
- WebSocket 实时推送
- React、Vue 或 Node.js 中的自定义事件发射器
4. 工厂模式
它是什么
在不暴露创建细节的情况下生成对象。
示例
function createUser(type) {
if (type === "admin") return { role: "admin", canDelete: true };
return { role: "user", canDelete: false };
}
何时使用
- 条件化对象创建
- 多版本 API
- 数据适配器
真实案例
支付集成(Stripe、PayPal、Razorpay)返回的响应结构各不相同。工厂可以将它们统一为一个通用接口,供整个应用使用。
5. 策略模式
它是什么
定义可互换的算法,并在运行时动态选择。
示例
const feeStrategies = {
credit: amt => amt * 0.02,
upi: amt => amt * 0,
debit: amt => amt * 0.01,
};
function calculateFee(method, amount) {
return feeStrategies[method](amount);
}
何时使用
- 动态业务逻辑
- 替代冗长的
if‑else链 - 定价或折扣计算
真实案例
- 支付费用计算
- 列表排序函数
- 基于功能开关的行为切换
6. 装饰器模式
它是什么
通过包装函数或对象来扩展行为,而不修改原始代码。
示例
function withLog(fn) {
return (...args) => {
console.log("Running", fn.name);
return fn(...args);
};
}
何时使用
- 日志记录
- 缓存
- 节流 / 防抖
- 授权包装
真实案例
- React 高阶组件(
withAuth) - Axios 拦截器
- 性能测量包装器
7. 代理模式
它是什么
拦截对对象的交互。
示例
const user = { name: "Ani" };
const proxy = new Pr```
> **Source:** ...
```js
oxy(user, {
get(target, prop) {
console.log("Access:", prop);
return target[prop];
}
});
何时使用
- 验证
- 访问控制
- 响应式
- 记忆化
真实场景使用
Vue 3 的整个响应式系统都是基于 Proxy 构建的。
8. 命令模式
它是什么
将操作封装为对象(执行 + 撤销)。
示例
class Command {
constructor(execute, undo) {
this.execute = execute;
this.undo = undo;
}
}
何时使用
- 撤销/重做功能
- 历史记录跟踪
- 宏操作
真实场景使用
- Figma 撤销栈
- VS Code 命令面板
- 类浏览器的导航历史
9. 适配器模式
它是什么
将不兼容的接口转换为可用的接口。
示例
function axiosToFetch(response) {
return {
status: response.status,
data: response.data,
};
}
何时使用
- 迁移代码库
- 集成第三方 API
- 统一不一致的数据
真实场景使用
将 axios 响应包装成统一格式,以便你的 API