JavaScript设计模式实例详解:从入门到精通
设计模式(design patterns)是软件开发中典型问题的成熟解决方案。在JavaScript(尤其是Node.js环境)中,理解这些模式有助于编写更清晰、模块化和可扩展的代码。本文将结合实际示例,解析设计模式的主要分类。
1. 创建型模式(Creational Patterns)
这类模式负责管理对象的创建过程,使系统独立于对象的实例化方式。
1.1. 单例模式(Singleton)
确保一个类只有一个实例,并提供全局访问点。在Node.js中,模块默认会被缓存,这简化了单例的实现。
class DatabaseConnection { constructor() { if (DatabaseConnection.instance) { return DatabaseConnection.instance; } this.connection = null; DatabaseConnection.instance = this; }
connect() { if (!this.connection) { this.connection = { status: 'connected' }; console.log('新数据库连接'); } return this.connection; }}
const db1 = new DatabaseConnection();const db2 = new DatabaseConnection();console.log(db1 === db2); // true1.2. 工厂方法模式(Factory Method)
定义一个创建对象的接口,但允许子类决定实例化哪个类。非常适合创建不同类型的日志记录器。
class LoggerFactory { createLogger(type) { switch (type) { case 'console': return new ConsoleLogger(); case 'file': return new FileLogger(); default: throw new Error('未知的日志记录器类型'); } }}
class ConsoleLogger { log(message) { console.log(message); }}
class FileLogger { log(message) { console.log(`[文件]: ${message}`); }}
const factory = new LoggerFactory();const logger = factory.createLogger('console');logger.log('测试消息');2. 结构型模式(Structural Patterns)
描述如何组合类和对象以形成更大的结构。
2.1. 装饰器模式(Decorator)
动态地为对象添加新职责。在JavaScript中,装饰器通常通过高阶函数或原型实现。
class Coffee { cost() { return 10; } description() { return '咖啡'; }}
function withMilk(coffee) { coffee.cost = () => coffee.cost() + 5; coffee.description = () => coffee.description() + ', 加牛奶'; return coffee;}
function withSugar(coffee) { coffee.cost = () => coffee.cost() + 2; coffee.description = () => coffee.description() + ', 加糖'; return coffee;}
let myCoffee = new Coffee();myCoffee = withMilk(myCoffee);myCoffee = withSugar(myCoffee);console.log(`${myCoffee.description()}: ${myCoffee.cost()} 元`); // 咖啡, 加牛奶, 加糖: 17 元2.2. 适配器模式(Adapter)
将一个类的接口转换成客户端期望的另一个接口。在集成第三方库时特别有用。
class OldAPI { getUserData() { return { name: '伊万', age: 25, email: 'ivan@example.com' }; }}
class NewAPI { fetchUser() { return { fullName: '伊万·彼得罗夫', yearsOld: 26, contact: 'ivan@example.com' }; }}
class UserAdapter { constructor(api) { this.api = api; }
getUserData() { const data = this.api.fetchUser(); return { name: data.fullName, age: data.yearsOld, email: data.contact }; }}
const adapter = new UserAdapter(new NewAPI());console.log(adapter.getUserData()); // { name: '伊万·彼得罗夫', age: 26, email: 'ivan@example.com' }3. 行为型模式(Behavioral Patterns)
定义算法