技术文摘
必知的 5 种 TypeScript 设计模式
2024-12-31 07:59:18 小编
必知的 5 种 TypeScript 设计模式
在 TypeScript 开发中,合理运用设计模式能够极大地提升代码的可维护性、可扩展性和可读性。以下为您介绍 5 种必知的 TypeScript 设计模式。
1. 单例模式(Singleton Pattern)
单例模式确保一个类只有一个实例存在,并提供一个全局访问点。在 TypeScript 中,可以通过将构造函数私有化,并提供一个静态方法来获取唯一实例来实现。
class Singleton {
private static instance: Singleton;
private constructor() {}
static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
}
2. 工厂模式(Factory Pattern)
工厂模式用于创建对象,将对象的创建与使用分离。通过定义一个工厂类,根据不同的条件创建不同的对象。
interface Product {
operation(): void;
}
class ConcreteProductA implements Product {
operation() {
console.log('ConcreteProductA operation');
}
}
class ConcreteProductB implements Product {
operation() {
console.log('ConcreteProductB operation');
}
}
class Factory {
createProduct(type: string): Product {
if (type === 'A') {
return new ConcreteProductA();
} else if (type === 'B') {
return new ConcreteProductB();
}
throw new Error('Invalid product type');
}
}
3. 观察者模式(Observer Pattern)
观察者模式定义了一种一对多的依赖关系,当一个对象状态发生改变时,所有依赖它的对象都会得到通知并自动更新。
interface Observer {
update(): void;
}
class Subject {
private observers: Observer[] = [];
attach(observer: Observer) {
this.observers.push(observer);
}
notify() {
for (const observer of this.observers) {
observer.update();
}
}
}
class ConcreteObserverA implements Observer {
update() {
console.log('ConcreteObserverA updated');
}
}
class ConcreteObserverB implements Observer {
update() {
console.log('ConcreteObserverB updated');
}
}
4. 策略模式(Strategy Pattern)
策略模式定义了一系列算法,并将每个算法封装起来,使它们可以相互替换。
interface Strategy {
execute(): void;
}
class StrategyA implements Strategy {
execute() {
console.log('StrategyA executed');
}
}
class StrategyB implements Strategy {
execute() {
console.log('StrategyB executed');
}
}
class Context {
private strategy: Strategy;
setStrategy(strategy: Strategy) {
this.strategy = strategy;
}
performStrategy() {
this.strategy.execute();
}
}
5. 装饰器模式(Decorator Pattern)
装饰器模式动态地给对象添加额外的职责,而不改变其结构。
function logDecorator(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log(`Calling ${propertyKey} with arguments: ${JSON.stringify(args)}`);
const result = originalMethod.apply(this, args);
console.log(`Result of ${propertyKey}: ${result}`);
return result;
};
return descriptor;
}
class Component {
@logDecorator
method() {
return 'Hello, Decorator!';
}
}
熟练掌握这些 TypeScript 设计模式,能够让您的代码更加优雅、高效和易于维护。在实际开发中,根据具体的业务需求合理选择和应用设计模式,将为您的项目带来更好的架构和质量。
- 浏览器调试窗口尺寸不一致:window.outerWidth与window.innerWidth差异原因
- 微信扫码登录后怎样自动关闭弹窗并刷新主窗口
- 为何用 标签播放音频资源失败,而用 标签能成功
- CSS与JavaScript实现表格横向排列、点击按钮生成新表格右移且操作按钮位置不变方法
- 用遮罩动画在Vue 3中实现图像轮播效果的方法
- 支持年、季度、月、周、日等多时间范围选择的开源 JS 时间插件有哪些
- 修改DOM元素ID后CSS样式失效的原因
- 为何 a 标签可直接播放音频,audio 标签却不能播放
- Flex布局怎样实现书签的垂直水平均匀分布
- 前端JavaScript中MD5加密数组的使用方法
- PC端多屏适配及PC兼响应式H5项目的实现方法
- CSS 中透明度(opacity)是否影响元素层级顺序
- PC 端多屏适配与 PC 兼响应式 H5 项目的实现方法
- JavaScript 中 void 0 代表什么及如何使用
- Echarts地图鼠标移入显示NaN问题及数据赋值为空解决方法