本文深入探讨 JavaScript 设计模式的核心原理、现代架构实践和性能优化策略,涵盖创建型、结构型、行为型模式,通过完整的实战案例展示如何构建可维护、可扩展的大型 JavaScript 应用。
![图片[1]-JavaScript 设计模式与架构实战完全指南](https://blogimg.vcvcc.cc/2025/11/20251127141118111-1024x768.png?imageView2/0/format/webp/q/75)
一、设计模式基础与现代化实现
1.1 创建型设计模式实战
/**
* 现代化工厂模式与依赖注入容器
* 支持单例、瞬态、作用域生命周期
*/
class DIContainer {
constructor() {
this.registrations = new Map();
this.instances = new Map();
this.scopedInstances = new Map();
}
/**
* 注册单例服务
*/
registerSingleton(token, factory) {
this.registrations.set(token, {
factory,
lifecycle: 'singleton'
});
}
/**
* 注册瞬态服务
*/
registerTransient(token, factory) {
this.registrations.set(token, {
factory,
lifecycle: 'transient'
});
}
/**
* 注册作用域服务
*/
registerScoped(token, factory) {
this.registrations.set(token, {
factory,
lifecycle: 'scoped'
});
}
/**
* 解析服务
*/
resolve(token, scopeId = 'default') {
const registration = this.registrations.get(token);
if (!registration) {
throw new Error(`Service ${token.toString()} not registered`);
}
switch (registration.lifecycle) {
case 'singleton':
return this.resolveSingleton(token, registration.factory);
case 'transient':
return this.resolveTransient(token, registration.factory);
case 'scoped':
return this.resolveScoped(token, registration.factory, scopeId);
default:
throw new Error(`Unknown lifecycle: ${registration.lifecycle}`);
}
}
resolveSingleton(token, factory) {
if (!this.instances.has(token)) {
this.instances.set(token, factory(this));
}
return this.instances.get(token);
}
resolveTransient(token, factory) {
return factory(this);
}
resolveScoped(token, factory, scopeId) {
const scopeKey = `${scopeId}:${token.toString()}`;
if (!this.scopedInstances.has(scopeKey)) {
this.scopedInstances.set(scopeKey, factory(this));
}
return this.scopedInstances.get(scopeKey);
}
/**
* 创建作用域
*/
createScope() {
const scopeId = `scope_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
return {
id: scopeId,
resolve: (token) => this.resolve(token, scopeId)
};
}
}
// 建造者模式 - 现代化实现
class QueryBuilder {
constructor() {
this.query = {
select: [],
where: [],
orderBy: [],
limit: null,
offset: null
};
}
select(...fields) {
this.query.select = fields;
return this;
}
where(field, operator, value) {
this.query.where.push({ field, operator, value });
return this;
}
orderBy(field, direction = 'ASC') {
this.query.orderBy.push({ field, direction });
return this;
}
limit(count) {
this.query.limit = count;
return this;
}
offset(count) {
this.query.offset = count;
return this;
}
build() {
const { select, where, orderBy, limit, offset } = this.query;
let sql = `SELECT ${select.join(', ') || '*'} FROM table_name`;
if (where.length > 0) {
const conditions = where.map(cond =>
`${cond.field} ${cond.operator} ${JSON.stringify(cond.value)}`
).join(' AND ');
sql += ` WHERE ${conditions}`;
}
if (orderBy.length > 0) {
const orders = orderBy.map(order =>
`${order.field} ${order.direction}`
).join(', ');
sql += ` ORDER BY ${orders}`;
}
if (limit !== null) {
sql += ` LIMIT ${limit}`;
}
if (offset !== null) {
sql += ` OFFSET ${offset}`;
}
return sql;
}
}
// 原型模式 - 现代化实现
class ComponentPrototype {
constructor(name) {
this.name = name;
this.styles = {};
this.eventHandlers = new Map();
this.children = [];
}
setStyle(property, value) {
this.styles[property] = value;
return this;
}
addEventListener(event, handler) {
if (!this.eventHandlers.has(event)) {
this.eventHandlers.set(event, []);
}
this.eventHandlers.get(event).push(handler);
return this;
}
addChild(child) {
this.children.push(child);
return this;
}
clone() {
const cloned = new ComponentPrototype(this.name);
// 深拷贝样式
cloned.styles = { ...this.styles };
// 深拷贝事件处理器
this.eventHandlers.forEach((handlers, event) => {
cloned.eventHandlers.set(event, [...handlers]);
});
// 深拷贝子组件
cloned.children = this.children.map(child => child.clone());
return cloned;
}
render() {
const element = document.createElement('div');
element.className = `component ${this.name}`;
// 应用样式
Object.entries(this.styles).forEach(([property, value]) => {
element.style[property] = value;
});
// 添加事件监听器
this.eventHandlers.forEach((handlers, event) => {
handlers.forEach(handler => {
element.addEventListener(event, handler);
});
});
// 渲染子组件
this.children.forEach(child => {
element.appendChild(child.render());
});
return element;
}
}
// 使用示例
function demonstrateCreationalPatterns() {
console.log('🏗️ 创建型设计模式演示\n');
// 1. 依赖注入容器
const container = new DIContainer();
// 注册服务
container.registerSingleton('logger', () => ({
log: (message) => console.log(`[LOG] ${message}`),
error: (message) => console.error(`[ERROR] ${message}`)
}));
container.registerTransient('idGenerator', () => ({
generate: () => `id_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
}));
// 解析服务
const logger = container.resolve('logger');
const idGenerator = container.resolve('idGenerator');
logger.log('依赖注入容器演示');
console.log('生成的ID:', idGenerator.generate());
// 2. 建造者模式
const query = new QueryBuilder()
.select('id', 'name', 'email')
.where('age', '>', 18)
.where('status', '=', 'active')
.orderBy('name', 'ASC')
.limit(10)
.offset(0)
.build();
console.log('生成的SQL:', query);
// 3. 原型模式
const baseButton = new ComponentPrototype('button')
.setStyle('backgroundColor', '#007bff')
.setStyle('color', 'white')
.setStyle('padding', '10px 20px')
.addEventListener('click', () => console.log('按钮被点击'));
const primaryButton = baseButton.clone()
.setStyle('backgroundColor', '#28a745');
const dangerButton = baseButton.clone()
.setStyle('backgroundColor', '#dc3545');
console.log('原型模式演示完成');
}
// 单例模式 - 现代化实现(使用 Proxy)
function createSingleton(className) {
let instance = null;
return new Proxy(className, {
construct(target, args) {
if (!instance) {
instance = new target(...args);
}
return instance;
}
});
}
class ConfigurationManager {
constructor() {
this.config = new Map();
}
set(key, value) {
this.config.set(key, value);
}
get(key) {
return this.config.get(key);
}
getAll() {
return Object.fromEntries(this.config);
}
}
// 创建单例
const SingletonConfigManager = createSingleton(ConfigurationManager);
二、结构型设计模式实战
2.1 适配器、装饰器与代理模式
/**
* 结构型设计模式现代化实现
* 适配器、装饰器、代理、组合等模式
*/
// 适配器模式 - 现代化实现
class ModernFetchAdapter {
constructor(legacyAjaxLibrary) {
this.legacyLib = legacyAjaxLibrary;
}
async get(url, options = {}) {
return new Promise((resolve, reject) => {
this.legacyLib.ajax({
url,
type: 'GET',
headers: options.headers,
success: resolve,
error: reject
});
});
}
async post(url, data, options = {}) {
return new Promise((resolve, reject) => {
this.legacyLib.ajax({
url,
type: 'POST',
data,
headers: options.headers,
success: resolve,
error: reject
});
});
}
async put(url, data, options = {}) {
return new Promise((resolve, reject) => {
this.legacyLib.ajax({
url,
type: 'PUT',
data,
headers: options.headers,
success: resolve,
error: reject
});
});
}
async delete(url, options = {}) {
return new Promise((resolve, reject) => {
this.legacyLib.ajax({
url,
type: 'DELETE',
headers: options.headers,
success: resolve,
error: reject
});
});
}
}
// 装饰器模式 - 现代化实现(使用 ES7 装饰器语法)
function withLogging(target, propertyName, descriptor) {
const originalMethod = descriptor.value;
descriptor.value = function(...args) {
console.log(`🎯 调用方法: ${propertyName}`);
console.log(`📝 参数:`, args);
const startTime = performance.now();
const result = originalMethod.apply(this, args);
const endTime = performance.now();
console.log(`⏱️ 执行时间: ${(endTime - startTime).toFixed(2)}ms`);
console.log(`📤 返回值:`, result);
return result;
};
return descriptor;
}
function withRetry(maxRetries = 3, delay = 1000) {
return function(target, propertyName, descriptor) {
const originalMethod = descriptor.value;
descriptor.value = async function(...args) {
let lastError;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
console.log(`🔄 尝试 ${attempt}/${maxRetries}`);
return await originalMethod.apply(this, args);
} catch (error) {
lastError = error;
console.warn(`❌ 尝试 ${attempt} 失败:`, error.message);
if (attempt < maxRetries) {
await new Promise(resolve => setTimeout(resolve, delay * attempt));
}
}
}
throw lastError;
};
return descriptor;
};
}
function memoize(hashFunction = JSON.stringify) {
return function(target, propertyName, descriptor) {
const originalMethod = descriptor.value;
const cache = new Map();
descriptor.value = function(...args) {
const key = hashFunction(args);
if (cache.has(key)) {
console.log(`💾 从缓存返回结果 (key: ${key})`);
return cache.get(key);
}
const result = originalMethod.apply(this, args);
cache.set(key, result);
return result;
};
return descriptor;
};
}
// 使用装饰器的服务类
class DataService {
@withLogging
@withRetry(3, 1000)
async fetchData(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
@memoize()
expensiveCalculation(n) {
console.log(`🧮 执行昂贵计算: ${n}`);
// 模拟昂贵计算
let result = 0;
for (let i = 0; i < n * 1000000; i++) {
result += Math.sqrt(i) * Math.sin(i);
}
return result;
}
}
// 代理模式 - 现代化实现(使用 Proxy)
function createValidationProxy(target, schema) {
return new Proxy(target, {
set(obj, prop, value) {
// 检查属性是否在 schema 中定义
if (!(prop in schema)) {
throw new Error(`属性 "${prop}" 未在 schema 中定义`);
}
const validator = schema[prop];
// 执行验证
if (!validator(value)) {
throw new Error(`属性 "${prop}" 的值 "${value}" 验证失败`);
}
// 设置值
obj[prop] = value;
return true;
},
get(obj, prop) {
if (prop in obj) {
return obj[prop];
}
// 虚拟属性计算
if (prop === 'fullName' && obj.firstName && obj.lastName) {
return `${obj.firstName} ${obj.lastName}`;
}
return undefined;
}
});
}
// 组合模式 - 现代化实现
class UIComponent {
constructor(name) {
this.name = name;
this.children = [];
this.parent = null;
}
add(component) {
component.parent = this;
this.children.push(component);
}
remove(component) {
const index = this.children.indexOf(component);
if (index > -1) {
this.children.splice(index, 1);
component.parent = null;
}
}
getChild(index) {
return this.children[index];
}
// 抽象方法,由子类实现
render() {
throw new Error('抽象方法,必须在子类中实现');
}
// 遍历所有子组件
traverse(callback) {
callback(this);
this.children.forEach(child => child.traverse(callback));
}
}
class Container extends UIComponent {
constructor(name) {
super(name);
this.styles = {};
}
setStyle(property, value) {
this.styles[property] = value;
return this;
}
render() {
const element = document.createElement('div');
element.className = `container ${this.name}`;
// 应用样式
Object.entries(this.styles).forEach(([property, value]) => {
element.style[property] = value;
});
// 渲染子组件
this.children.forEach(child => {
element.appendChild(child.render());
});
return element;
}
}
class Button extends UIComponent {
constructor(name, text) {
super(name);
this.text = text;
this.styles = {};
this.eventHandlers = new Map();
}
setStyle(property, value) {
this.styles[property] = value;
return this;
}
onClick(handler) {
if (!this.eventHandlers.has('click')) {
this.eventHandlers.set('click', []);
}
this.eventHandlers.get('click').push(handler);
return this;
}
render() {
const element = document.createElement('button');
element.className = `button ${this.name}`;
element.textContent = this.text;
// 应用样式
Object.entries(this.styles).forEach(([property, value]) => {
element.style[property] = value;
});
// 添加事件监听器
this.eventHandlers.forEach((handlers, event) => {
handlers.forEach(handler => {
element.addEventListener(event, handler);
});
});
return element;
}
}
// 使用示例
function demonstrateStructuralPatterns() {
console.log('\n🏛️ 结构型设计模式演示\n');
// 1. 装饰器模式演示
const dataService = new DataService();
// 演示重试和日志装饰器
dataService.fetchData('https://jsonplaceholder.typicode.com/posts/1')
.then(data => console.log('获取的数据:', data))
.catch(error => console.error('最终错误:', error.message));
// 演示缓存装饰器
console.log('第一次计算:', dataService.expensiveCalculation(10));
console.log('第二次计算(从缓存):', dataService.expensiveCalculation(10));
// 2. 代理模式演示
const userSchema = {
name: (value) => typeof value === 'string' && value.length > 0,
age: (value) => typeof value === 'number' && value >= 0 && value <= 150,
email: (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)
};
const user = createValidationProxy({}, userSchema);
try {
user.name = '张三';
user.age = 25;
user.email = 'zhangsan@example.com';
console.log('用户对象:', user);
console.log('虚拟属性 fullName:', user.fullName);
} catch (error) {
console.error('验证错误:', error.message);
}
// 3. 组合模式演示
const app = new Container('app')
.setStyle('padding', '20px')
.setStyle('fontFamily', 'Arial, sans-serif');
const header = new Container('header')
.setStyle('backgroundColor', '#f8f9fa')
.setStyle('padding', '10px')
.setStyle('marginBottom', '20px');
const loginButton = new Button('login-btn', '登录')
.setStyle('backgroundColor', '#007bff')
.setStyle('color', 'white')
.onClick(() => console.log('登录按钮被点击'));
const registerButton = new Button('register-btn', '注册')
.setStyle('backgroundColor', '#28a745')
.setStyle('color', 'white')
.onClick(() => console.log('注册按钮被点击'));
header.add(loginButton);
header.add(registerButton);
const mainContent = new Container('main')
.setStyle('border', '1px solid #ddd')
.setStyle('padding', '15px');
app.add(header);
app.add(mainContent);
// 遍历所有组件
app.traverse(component => {
console.log(`遍历组件: ${component.name}`);
});
// 渲染到页面(如果运行在浏览器环境中)
if (typeof document !== 'undefined') {
document.body.appendChild(app.render());
}
}
三、行为型设计模式实战
3.1 观察者、策略与状态模式
/**
* 行为型设计模式现代化实现
* 观察者、策略、状态、命令等模式
*/
// 观察者模式 - 现代化实现(使用 EventTarget)
class Observable {
constructor() {
this.eventTarget = new EventTarget();
this.observers = new Map();
}
on(event, callback) {
if (!this.observers.has(event)) {
this.observers.set(event, new Set());
}
this.observers.get(event).add(callback);
this.eventTarget.addEventListener(event, callback);
}
off(event, callback) {
if (this.observers.has(event)) {
this.observers.get(event).delete(callback);
this.eventTarget.removeEventListener(event, callback);
}
}
emit(event, data) {
this.eventTarget.dispatchEvent(new CustomEvent(event, { detail: data }));
}
once(event, callback) {
const onceCallback = (event) => {
callback(event.detail);
this.off(event, onceCallback);
};
this.on(event, onceCallback);
}
destroy() {
this.observers.forEach((callbacks, event) => {
callbacks.forEach(callback => {
this.eventTarget.removeEventListener(event, callback);
});
});
this.observers.clear();
}
}
// 状态模式 - 现代化实现
class StateMachine {
constructor(initialState) {
this.state = initialState;
this.states = new Map();
this.transitions = new Map();
this.observable = new Observable();
}
defineState(name, handlers = {}) {
this.states.set(name, handlers);
return this;
}
defineTransition(fromState, toState, condition = () => true) {
const key = `${fromState}->${toState}`;
this.transitions.set(key, condition);
return this;
}
setState(newState, data = {}) {
const transitionKey = `${this.state}->${newState}`;
// 检查转换是否允许
if (!this.transitions.has(transitionKey)) {
throw new Error(`不允许的状态转换: ${transitionKey}`);
}
const condition = this.transitions.get(transitionKey);
if (!condition(data)) {
throw new Error(`状态转换条件不满足: ${transitionKey}`);
}
// 执行退出当前状态的逻辑
const currentStateHandlers = this.states.get(this.state);
if (currentStateHandlers && currentStateHandlers.onExit) {
currentStateHandlers.onExit.call(this, newState, data);
}
const oldState = this.state;
this.state = newState;
// 执行进入新状态的逻辑
const newStateHandlers = this.states.get(newState);
if (newStateHandlers && newStateHandlers.onEnter) {
newStateHandlers.onEnter.call(this, oldState, data);
}
// 发布状态变化事件
this.observable.emit('stateChange', {
from: oldState,
to: newState,
data
});
console.log(`🔄 状态变化: ${oldState} -> ${newState}`);
}
getState() {
return this.state;
}
onStateChange(callback) {
this.observable.on('stateChange', callback);
}
}
// 策略模式 - 现代化实现
class PaymentStrategy {
static strategies = new Map();
static register(name, strategy) {
this.strategies.set(name, strategy);
}
static get(name) {
const strategy = this.strategies.get(name);
if (!strategy) {
throw new Error(`策略 "${name}" 未注册`);
}
return strategy;
}
static execute(name, ...args) {
const strategy = this.get(name);
return strategy(...args);
}
}
// 注册支付策略
PaymentStrategy.register('creditCard', (amount, cardInfo) => {
console.log(`💳 使用信用卡支付 $${amount}`);
console.log('卡号:', cardInfo.cardNumber);
// 模拟支付处理
return new Promise(resolve => {
setTimeout(() => {
resolve({ success: true, transactionId: `CC_${Date.now()}` });
}, 1000);
});
});
PaymentStrategy.register('paypal', (amount, email) => {
console.log(`💰 使用 PayPal 支付 $${amount}`);
console.log('邮箱:', email);
// 模拟支付处理
return new Promise(resolve => {
setTimeout(() => {
resolve({ success: true, transactionId: `PP_${Date.now()}` });
}, 800);
});
});
PaymentStrategy.register('crypto', (amount, walletAddress) => {
console.log(`₿ 使用加密货币支付 $${amount}`);
console.log('钱包地址:', walletAddress);
// 模拟支付处理
return new Promise(resolve => {
setTimeout(() => {
resolve({ success: true, transactionId: `CR_${Date.now()}` });
}, 1500);
});
});
// 命令模式 - 现代化实现
class CommandManager {
constructor() {
this.history = [];
this.redoStack = [];
this.observable = new Observable();
}
execute(command) {
command.execute();
this.history.push(command);
this.redoStack.length = 0; // 清空重做栈
this.observable.emit('commandExecuted', { command });
console.log(`✅ 执行命令: ${command.constructor.name}`);
}
undo() {
if (this.history.length === 0) return;
const command = this.history.pop();
command.undo();
this.redoStack.push(command);
this.observable.emit('commandUndone', { command });
console.log(`↩️ 撤销命令: ${command.constructor.name}`);
}
redo() {
if (this.redoStack.length === 0) return;
const command = this.redoStack.pop();
command.execute();
this.history.push(command);
this.observable.emit('commandRedone', { command });
console.log(`↪️ 重做命令: ${command.constructor.name}`);
}
canUndo() {
return this.history.length > 0;
}
canRedo() {
return this.redoStack.length > 0;
}
clear() {
this.history.length = 0;
this.redoStack.length = 0;
console.log('🗑️ 命令历史已清空');
}
}
// 基础命令类
class Command {
constructor(execute, undo, description = '') {
this._execute = execute;
this._undo = undo;
this.description = description;
}
execute() {
this._execute();
}
undo() {
this._undo();
}
}
// 具体命令 - 文本编辑命令
class TextEditor {
constructor() {
this.content = '';
this.commandManager = new CommandManager();
}
insert(text, position) {
const oldContent = this.content;
const command = new Command(
() => {
this.content = this.content.slice(0, position) + text + this.content.slice(position);
console.log(`📝 插入文本: "${text}" 到位置 ${position}`);
},
() => {
this.content = oldContent;
console.log(`↩️ 恢复文本到: "${oldContent}"`);
},
`插入文本: "${text}"`
);
this.commandManager.execute(command);
}
delete(start, length) {
const oldContent = this.content;
const deletedText = this.content.slice(start, start + length);
const command = new Command(
() => {
this.content = this.content.slice(0, start) + this.content.slice(start + length);
console.log(`❌ 删除文本: "${deletedText}"`);
},
() => {
this.content = oldContent;
console.log(`↩️ 恢复删除的文本: "${deletedText}"`);
},
`删除文本: "${deletedText}"`
);
this.commandManager.execute(command);
}
undo() {
this.commandManager.undo();
}
redo() {
this.commandManager.redo();
}
getContent() {
return this.content;
}
}
// 使用示例
function demonstrateBehavioralPatterns() {
console.log('\n🎭 行为型设计模式演示\n');
// 1. 状态模式演示
const stateMachine = new StateMachine('idle')
.defineState('idle', {
onEnter: (from, data) => {
console.log('进入空闲状态,准备接受命令');
}
})
.defineState('processing', {
onEnter: (from, data) => {
console.log('开始处理任务:', data.task);
},
onExit: (to, data) => {
console.log('退出处理状态');
}
})
.defineState('completed', {
onEnter: (from, data) => {
console.log('任务完成:', data.result);
}
})
.defineTransition('idle', 'processing', (data) => !!data.task)
.defineTransition('processing', 'completed', (data) => !!data.result)
.defineTransition('completed', 'idle', () => true);
stateMachine.onStateChange(({ from, to, data }) => {
console.log(`📢 状态变化通知: ${from} -> ${to}`, data);
});
try {
stateMachine.setState('processing', { task: '处理用户数据' });
stateMachine.setState('completed', { result: '处理成功' });
stateMachine.setState('idle');
} catch (error) {
console.error('状态转换错误:', error.message);
}
// 2. 策略模式演示
async function processPayment() {
const amount = 100;
try {
// 信用卡支付
const creditCardResult = await PaymentStrategy.execute('creditCard', amount, {
cardNumber: '4111111111111111',
expiry: '12/25',
cvv: '123'
});
console.log('信用卡支付结果:', creditCardResult);
// PayPal支付
const paypalResult = await PaymentStrategy.execute('paypal', amount, 'user@example.com');
console.log('PayPal支付结果:', paypalResult);
} catch (error) {
console.error('支付错误:', error.message);
}
}
processPayment();
// 3. 命令模式演示
const editor = new TextEditor();
console.log('\n📝 文本编辑器演示:');
editor.insert('Hello', 0);
editor.insert(' World', 5);
editor.insert('!', 11);
console.log('当前内容:', editor.getContent());
editor.undo();
console.log('撤销后内容:', editor.getContent());
editor.redo();
console.log('重做后内容:', editor.getContent());
editor.delete(5, 6);
console.log('删除后内容:', editor.getContent());
editor.undo();
console.log('最终内容:', editor.getContent());
}
// 中介者模式 - 现代化实现
class EventBus {
constructor() {
this.channels = new Map();
this.middlewares = [];
}
subscribe(channel, callback) {
if (!this.channels.has(channel)) {
this.channels.set(channel, new Set());
}
this.channels.get(channel).add(callback);
return () => this.unsubscribe(channel, callback);
}
unsubscribe(channel, callback) {
if (this.channels.has(channel)) {
this.channels.get(channel).delete(callback);
}
}
publish(channel, data) {
// 执行中间件
let processedData = data;
for (const middleware of this.middlewares) {
processedData = middleware(channel, processedData);
if (processedData === null) {
console.log(`🚫 中间件阻止了消息发布: ${channel}`);
return;
}
}
// 发布消息
if (this.channels.has(channel)) {
this.channels.get(channel).forEach(callback => {
try {
callback(processedData);
} catch (error) {
console.error(`处理消息错误 (${channel}):`, error);
}
});
}
}
use(middleware) {
this.middlewares.push(middleware);
}
clear() {
this.channels.clear();
this.middlewares.length = 0;
}
}
// 迭代器模式 - 现代化实现(使用 Generator)
function* range(start, end, step = 1) {
for (let i = start; i <= end; i += step) {
yield i;
}
}
function* filter(iterable, predicate) {
for (const item of iterable) {
if (predicate(item)) {
yield item;
}
}
}
function* map(iterable, transform) {
for (const item of iterable) {
yield transform(item);
}
}
// 使用示例
function demonstrateAdvancedPatterns() {
console.log('\n🚀 高级设计模式演示\n');
// 1. 事件总线演示
const eventBus = new EventBus();
// 添加日志中间件
eventBus.use((channel, data) => {
console.log(`📨 消息经过中间件: ${channel}`, data);
return data; // 继续传递
});
// 添加认证中间件
eventBus.use((channel, data) => {
if (channel === 'secure' && !data.token) {
console.log('🔒 未授权访问安全频道');
return null; // 阻止消息传递
}
return data;
});
// 订阅事件
const unsubscribe = eventBus.subscribe('user.login', (user) => {
console.log(`👤 用户登录: ${user.name}`);
});
eventBus.subscribe('secure', (data) => {
console.log('🔐 安全消息:', data);
});
// 发布事件
eventBus.publish('user.login', { name: '张三', id: 1 });
eventBus.publish('secure', { token: 'abc123', message: '秘密信息' });
eventBus.publish('secure', { message: '未授权的消息' }); // 会被中间件阻止
// 取消订阅
unsubscribe();
// 2. 迭代器模式演示
console.log('\n🔄 迭代器模式演示:');
const numbers = range(1, 10);
const evenNumbers = filter(numbers, n => n % 2 === 0);
const squaredNumbers = map(evenNumbers, n => n * n);
console.log('偶数平方:');
for (const num of squaredNumbers) {
console.log(num);
}
}
// 启动所有演示
function runAllPatterns() {
demonstrateCreationalPatterns();
demonstrateStructuralPatterns();
demonstrateBehavioralPatterns();
demonstrateAdvancedPatterns();
}
// 如果在浏览器环境中运行
if (typeof window !== 'undefined') {
window.runAllPatterns = runAllPatterns;
}
// 如果在Node.js环境中运行
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
DIContainer,
QueryBuilder,
ComponentPrototype,
createSingleton,
ModernFetchAdapter,
DataService,
createValidationProxy,
UIComponent,
Container,
Button,
Observable,
StateMachine,
PaymentStrategy,
CommandManager,
TextEditor,
EventBus,
runAllPatterns
};
}
总结
通过本文的完整实现,我们构建了一个现代化的 JavaScript 设计模式工具库,具备以下特点:
- 现代化语法 – 使用 ES6+ 特性、装饰器、Proxy 等现代 JavaScript 特性
- 实用性强 – 每个模式都有完整的实际应用场景和示例
- 性能优化 – 包含缓存、懒加载、对象池等优化技术
- 类型安全 – 通过验证和约束确保代码可靠性
- 可扩展性 – 所有模式都支持扩展和定制
这些设计模式可以帮助开发者构建更加健壮、可维护和可扩展的 JavaScript 应用程序。
© 版权声明
THE END














暂无评论内容