必知的 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 设计模式,能够让您的代码更加优雅、高效和易于维护。在实际开发中,根据具体的业务需求合理选择和应用设计模式,将为您的项目带来更好的架构和质量。

TAGS: 设计模式种类 TypeScript 应用 必知的知识 TypeScript 设计模式

欢迎使用万千站长工具!

Welcome to www.zzTool.com