以下是前端工程师需要掌握的 15 个 JavaScript 高级设计模式实战解析,结合现代开发场景和 ES6+ 特性:
场景:封装私有变量 + 公共 API 暴露
const Counter = (() => {
let count = 0; // 私有变量
return {
increment: () => ++count,
getCount: () => count
};
})();
Counter.increment();
console.log(Counter.getCount()); // 1
应用:工具库封装、避免全局污染
场景: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;
};
}
});
优势:透明化缓存逻辑,降低主业务耦合
场景:实现自定义事件系统
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));
}
}
// 使用案例:组件间通信
场景:React HOC 高阶组件
const withLogger = (WrappedComponent) => {
return class extends React.Component {
componentDidMount() {
console.log(`Component ${WrappedComponent.name} mounted`);
}
render() {
return <WrappedComponent {...this.props} />;
}
};
};
场景:表单验证规则切换
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);
场景:树形菜单组件
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>
`;
}
}
场景:订单状态机
class Order {
constructor() {
this.state = new PendingState();
}
nextState() {
this.state = this.state.next();
}
}
class ShippedState {
next() {
return new DeliveredState();
}
}
场景:动态创建 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');
}
}
}
场景:全局状态管理
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
场景:兼容新旧接口
class LegacyAPI {
requestLegacy() { /*...*/ }
}
class NewAPIAdapter {
constructor(legacyApi) {
this.legacyApi = legacyApi;
}
fetch() {
return this.legacyApi.requestLegacy().then(transformData);
}
}
场景:实现撤销/重做功能
class EditorHistory {
constructor() {
this.states = [];
}
push(state) {
this.states.push(JSON.stringify(state));
}
pop() {
return JSON.parse(this.states.pop());
}
}
场景:中间件管道
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();
}
场景:算法骨架定义
class DataProcessor {
process() {
this.validate();
this.transform();
this.save();
}
validate() { /* 默认实现 */ }
abstract transform(); // 需子类实现
save() { /* 默认实现 */ }
}
场景:优化大量相似对象
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);
}
}
场景:解耦服务依赖
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);
掌握这些模式的关键在于理解其适用场景,而非强行套用。建议通过实际项目中的复杂问题来驱动模式的选择和优化。