- 设计模式是提升代码可维护性、可扩展性和可复用的重要工具
创建型模式
工厂模式
- 封装对象的创建过程,通过函数或类统一生成实例,避免直接使用 new 关键字
- 简单工厂:通过函数返回不同对象实例
function createButton(type) {
if (type === 'primary') return { color: 'blue' };
else if (type === 'danger') return { color: 'red' };
}
示例2
class Circle { draw() { console.log('Draw Circle'); } }
class Square { draw() { console.log('Draw Square'); } }
class ShapeFactory {
static create(type) {
switch(type) {
case 'circle': return new Circle();
case 'square': return new Square();
default: throw new Error('Unknown shape');
}
}
}
const shape1 = ShapeFactory.create('circle');
shape1.draw(); // Draw Circle
- 应用场景:组件库(如根据类型生成不同 UI 组件
抽象工厂模式
抽象工厂提供一个接口,用于创建一系列相关或相互依赖的对象,而无需指定其具体类。
TutorialsPoint 适合需要同时创建多个具有同一主题的产品族时,例如皮肤主题下按钮、输入框、弹窗的统一创建
// 抽象产品接口
class Button { render() {} }
class Modal { open() {} }
// 具体产品:Light 主题
class LightButton extends Button { render() { console.log('Light Button'); } }
class LightModal extends Modal { open() { console.log('Light Modal'); } }
// 抽象工厂接口
class UIAbstractFactory {
createButton() {}
createModal() {}
}
// 具体工厂:Light
class LightFactory extends UIAbstractFactory {
createButton() { return new LightButton(); }
createModal() { return new LightModal(); }
}
// 客户端
function initUI(factory) {
const btn = factory.createButton();
const modal = factory.createModal();
btn.render(); modal.open();
}
initUI(new LightFactory());
- 通过替换工厂即可切换整套 UI 产品族
单例模式
- 单例模式确保一个类只有一个实例,并提供全局访问点。GeeksforGeeks适用于需要全局唯一配置或管理器的场景,如日志管理、缓存管理等
class Singleton {
constructor(value) {
if (Singleton.instance) {
return Singleton.instance;
}
this.value = value;
Singleton.instance = this;
}
}
const a = new Singleton(1);
const b = new Singleton(2);
console.log(a === b, a.value, b.value); // true, 1, 1
原型模式
- 原型模式使用已有对象作为原型,通过复制来创建新对象,从而减少新建对象的性能开销。重构大师适用于大量相似对象的场景,如动画游戏中重复出现的敌机实例
const prototypeObject = {
init(name) { this.name = name; },
clone() { return Object.create(this); }
};
const obj1 = prototypeObject.clone();
obj1.init('Alice');
console.log(obj1.name); // Alice
const obj2 = prototypeObject.clone();
obj2.init('Bob');
console.log(obj2.name); // Bob
结构型模式
模块模式
- 模块模式利用闭包创建私有变量和方法,只暴露公共接口,实现封装和命名空间管理。TutorialsPoint常见于前端脚本组织,如将 API 调用逻辑封装在独立模块中
const CounterModule = (function() {
let count = 0; // 私有
return {
increment() { count++; },
getCount() { return count; }
};
})();
CounterModule.increment();
console.log(CounterModule.getCount()); // 1
私有变量 count 只能通过暴露的方法访问,避免全局污染
装饰器模式
- 装饰器模式在不修改原有对象结构的前提下,动态地给对象添加职责或行为
- 适用于功能扩展,比如给函数添加日志、缓存或权限校验功能
function basicLogging(fn) {
return function(...args) {
console.log('Input:', args);
const result = fn(...args);
console.log('Output:', result);
return result;
};
}
function add(a, b) { return a + b; }
const loggedAdd = basicLogging(add);
loggedAdd(2, 3); // 日志 + 返回 5
用高阶函数包装原函数,实现“装饰”效果
外观模式
- 外观模式为复杂子系统提供统一、简化的接口,屏蔽内部复杂性
- 例如为浏览器的多种网络请求方式(XHR、fetch)提供统一调用入口。
const HttpFacade = {
get(url) { return fetch(url).then(res => res.json()); },
post(url, data) {
return fetch(url, {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify(data)
}).then(res => res.json());
}
};
HttpFacade.get('/api/data').then(console.log);
客户端无需关心底层实现细节
行为型模式
观察者模式
- 观察者模式定义对象间一对多的依赖,当目标对象状态改变时,自动通知所有观察者
- 适用于事件驱动或发布/订阅场景,如浏览器事件、MVC 中的模型-视图更新。
class Subject {
constructor() { this.observers = []; }
subscribe(o) { this.observers.push(o); }
unsubscribe(o) { this.observers = this.observers.filter(obs => obs !== o); }
notify(data) { this.observers.forEach(obs => obs.update(data)); }
}
class Observer {
update(data) { console.log('Received:', data); }
}
const subj = new Subject();
const obs = new Observer();
subj.subscribe(obs);
subj.notify('Hello'); // Observers 收到通知
策略模式
- 策略模式定义一系列算法,将每个算法封装成独立策略类,并使它们可以互换
- 适用于需在多种算法间切换的场景,如不同排序、不同折扣计算方式
const strategies = {
bubble: arr => { /* 冒泡排序实现 */ },
quick: arr => { /* 快速排序实现 */ }
};
function sort(arr, type) {
return strategies[type](arr);
}
console.log(sort([3,1,2], 'bubble'));
新增策略只需在 strategies 中注册即可
命令模式
- 命令模式将请求封装成对象,从而支持参数化、队列化及撤销操作
- 常用于实现可撤销操作、日志记录或事务系统。
class Command {
constructor(receiver, action) {
this.receiver = receiver; this.action = action;
}
execute() { this.receiver[this.action](); }
}
class Light { on() { console.log('Light ON'); } off() { console.log('Light OFF'); } }
const light = new Light();
const cmdOn = new Command(light, 'on');
cmdOn.execute(); // Light ON
命令可存储、排队或回滚