TypeScript 设计模式:示例与应用

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程
```html

TypeScript中的设计模式:实用指南



设计模式(design patterns)是软件开发中常见问题的经过验证的解决方案。在TypeScript中,由于严格的类型系统和面向对象编程(OOP)特性,许多模式实现得特别优雅且安全。在本文中,我们将通过实际代码示例分析四个关键模式,帮助您编写更灵活、更易维护的代码。



1. Singleton(单例模式)



Singleton模式确保一个类只有一个实例,并提供一个全局访问点。在TypeScript中,这对于管理应用程序配置或数据库连接特别有用。



使用私有构造函数和静态方法的实现:



class DatabaseConnection {  private static instance: DatabaseConnection;  private connection: string;

private constructor() { this.connection = 'PostgreSQL connected'; }

public static getInstance(): DatabaseConnection { if (!DatabaseConnection.instance) { DatabaseConnection.instance = new DatabaseConnection(); } return DatabaseConnection.instance; }

public query(sql: string): void { console.log(`Executing query: ${sql} on ${this.connection}`); }}

// 使用const db1 = DatabaseConnection.getInstance();const db2 = DatabaseConnection.getInstance();console.log(db1 === db2); // true - 同一个对象db1.query('SELECT * FROM users');


何时使用: 用于日志记录器、缓存、线程池、应用程序设置。避免在可能发生多线程环境变化的状态中使用Singleton。



2. Factory Method(工厂方法模式)



Factory Method定义了一个创建对象的接口,但允许子类更改所创建对象的类型。在TypeScript中,这与接口和抽象类配合得很好。



创建不同类型通知的示例:



interface Notification {  send(message: string): void;}

class EmailNotification implements Notification { public send(message: string): void { console.log(`Email sent: ${message}`); }}

class SMSNotification implements Notification { public send(message: string): void { console.log(`SMS sent: ${message}`); }}

abstract class NotificationFactory { public abstract createNotification(): Notification;

public notifyUser(message: string): void { const notification = this.createNotification(); notification.send(message); }}

class EmailNotificationFactory extends NotificationFactory { public createNotification(): Notification { return new EmailNotification(); }}

class SMSNotificationFactory extends NotificationFactory { public createNotification(): Notification { return new SMSNotification(); }}

// 使用const factory: NotificationFactory = new EmailNotificationFactory();factory.notifyUser('Your order has been shipped!');


何时使用: 当预先不知道需要哪个具体类时,或者当对象创建逻辑复杂且需要集中管理时。



3. Observer(观察者模式)



Observer定义了对象之间的一对多依赖关系:当一个对象的状态发生变化时,所有依赖对象都会自动收到通知。在TypeScript中,这通常通过泛型来实现事件类型化。



新闻订阅系统示例:



interface Observer<T> {  update(data: T): void;}

class NewsPublisher<T> { private observers: Observer<T>[] = [];

public subscribe(observer: Observer<T>): void { this.observers.push(observer); }

public unsubscribe(observer: Observer<T>): void { this.observers = this.observers.filter(obs => o ```

博客

书籍推荐