TypeScript 设计模式:从简单到复杂
设计模式 (design patterns) 是经过时间验证的、用于解决软件开发中常见问题的方案。在 TypeScript 的背景下,它为 JavaScript 增加了强类型和面向对象编程的能力,使得设计模式尤其有效。TypeScript 允许在更高层次上实现抽象、接口和多态,使代码更加可预测和安全。
在本文中,我们将分析关键的设计模式、它们在 TypeScript 中的实现以及实际使用示例。本材料对初学者开发者和希望系统化知识的有经验专家都很有帮助。
创建型模式:Singleton 和 Factory Method
创建型模式负责对象的创建,隐藏实例化的逻辑。我们来分析两个最流行的代表:Singleton 和 Factory Method。
Singleton(单例模式)
Singleton 确保一个类只有一个实例,并提供一个全局访问点。在 TypeScript 中,由于静态成员和私有构造函数的存在,实现变得特别优雅。
class DatabaseConnection { private static instance: DatabaseConnection; private connectionString: string;
private constructor(connectionString: string) { this.connectionString = connectionString; console.log(`已创建连接:${connectionString}`); }
static getInstance(connectionString: string): DatabaseConnection { if (!DatabaseConnection.instance) { DatabaseConnection.instance = new DatabaseConnection(connectionString); } return DatabaseConnection.instance; }
query(sql: string): void { console.log(`执行查询:${sql} 在 ${this.connectionString}`); }}
// 使用const db1 = DatabaseConnection.getInstance('postgres://localhost:5432/mydb');const db2 = DatabaseConnection.getInstance('postgres://localhost:5432/mydb');console.log(db1 === db2); // true - 同一个对象这个模式非常适合管理资源:连接池、日志记录、缓存。但要小心——Singleton 可能因全局状态而使测试变得复杂。
Factory Method(工厂方法模式)
Factory Method 定义了一个创建对象的接口,但允许子类更改所创建对象的类型。在 TypeScript 中,这通过抽象类或接口实现。
interface Notification { send(message: string): void;}
class EmailNotification implements Notification { send(message: string): void { console.log(`发送 email:${message}`); }}
class SMSNotification implements Notification { send(message: string): void { console.log(`发送 SMS:${message}`); }}
abstract class NotificationFactory { abstract createNotification(): Notification;
notify(message: string): void { const notification = this.createNotification(); notification.send(message); }}
class EmailFactory extends NotificationFactory { createNotification(): Notification { return new EmailNotification(); }}
class SMSFactory extends NotificationFactory { createNotification(): Notification { return new SMSNotification(); }}
// 使用const factory: NotificationFactory = new EmailFactory();factory.notify('您的订单已确认!');Factory Method 有助于遵守开闭原则 (OCP)——您可以在不修改现有代码的情况下添加新类型的通知。
结构型模式:Adapter 和 Decorator
结构型模式有助于组织对象和类之间的关系,使系统更加灵活和可扩展。