JavaScript常用设计模式包括单例、工厂、观察者等,其中单例确保全局唯一实例,适用于配置管理、日志等场景;工厂封装创建逻辑,用于按条件生成不同对象,二者依需求本质选择。
JavaScript 中常用的设计模式有单例模式、工厂模式、观察者模式、发布-订阅模式、代理模式、装饰器模式、策略模式、状态模式、适配器模式、迭代器模式等。其中单例和工厂模式最基础也最常用,适合解决对象创建和复用问题。
单例的核心是“全局唯一”和“延迟创建”。它常用于配置管理、日志记录、弹窗管理、状态存储等需要统一入口的场景。
示例(函数式单例):
const Logger = (function() {
let instance;
function create() {
return {
log: (msg) => console.log(`[LOG] ${new Date().toISOString()}: ${msg}`)
};
}
return {
getInstance: () => {
if (!instance) instance = create();
return instance;
}
};
})();
// 使用
const logger1 = Logger.getInstance();
const logger2 = Logger.getInstance();
console.log(logger1 === logger2); // true
工厂模式用于解耦“谁来创建对象”和“谁来使用对象”,尤其适合创建多种相似类型(如不同形状、支付方式、UI组件)的场景。
示例(简单工厂):
class Button {
constructor(type) {
this.type = type;
}
}
class Dialog {
constructor(theme) {
this.theme = theme;
}
}
// 工厂函数
function createUIElement(type, config) {
switch (type.toLowerCase()) {
case 'button': return new Button(config.style || 'default');
case 'dialog': return new Dialog(config.theme || 'light');
default: throw new Error(`Unknown UI type: ${type}`);
}
}
// 使用
const btn = createUIElement('button', { style: 'primary' });
const dlg = createUIElement('dialog', { theme: 'dark' });
看需求本质:
基本上就这些。不复杂但容易忽略细节——关键是理解意图,而不是死记代码结构。