返回

激发创造力:使用 TypeScript 深入探索创建型设计模式

前端

单例模式

单例模式是一种创建型设计模式,它确保一个类只有一个实例,并提供一个全局访问点来获取这个实例。单例模式通常用于创建全局配置对象、日志记录器或数据库连接池等。

在 TypeScript 中,我们可以使用以下代码来实现单例模式:

class Singleton {
  private static instance: Singleton;

  private constructor() {}

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

    return Singleton.instance;
  }
}

工厂模式

工厂模式是一种创建型设计模式,它通过使用一个工厂类来创建对象,而不是直接调用构造函数。工厂模式可以使代码更加灵活,因为你可以根据需要创建不同的对象,而无需修改客户端代码。

在 TypeScript 中,我们可以使用以下代码来实现工厂模式:

class Factory {
  public createProduct(type: string): Product {
    switch (type) {
      case "A":
        return new ProductA();
      case "B":
        return new ProductB();
      default:
        throw new Error("Invalid product type.");
    }
  }
}

class ProductA {
  public doSomething(): void {
    console.log("ProductA do something.");
  }
}

class ProductB {
  public doSomething(): void {
    console.log("ProductB do something.");
  }
}

const factory = new Factory();
const productA = factory.createProduct("A");
productA.doSomething(); // Output: ProductA do something.

const productB = factory.createProduct("B");
productB.doSomething(); // Output: ProductB do something.

建造者模式

建造者模式是一种创建型设计模式,它允许你使用不同的部件来构建一个复杂的对象。建造者模式可以使代码更加灵活,因为你可以根据需要创建不同的对象,而无需修改客户端代码。

在 TypeScript 中,我们可以使用以下代码来实现建造者模式:

class Builder {
  private product: Product;

  public constructor() {
    this.product = new Product();
  }

  public buildPartA(): void {
    this.product.addPartA();
  }

  public buildPartB(): void {
    this.product.addPartB();
  }

  public buildPartC(): void {
    this.product.addPartC();
  }

  public getProduct(): Product {
    return this.product;
  }
}

class Product {
  private parts: string[] = [];

  public addPartA(): void {
    this.parts.push("PartA");
  }

  public addPartB(): void {
    this.parts.push("PartB");
  }

  public addPartC(): void {
    this.parts.push("PartC");
  }

  public getParts(): string[] {
    return this.parts;
  }
}

const builder = new Builder();
builder.buildPartA();
builder.buildPartB();
builder.buildPartC();

const product = builder.getProduct();
console.log(product.getParts()); // Output: ["PartA", "PartB", "PartC"]

原型模式

原型模式是一种创建型设计模式,它允许你通过克隆一个现有的对象来创建一个新的对象。原型模式可以使代码更加高效,因为它不需要重新创建对象,而是直接克隆一个现有的对象。

在 TypeScript 中,我们可以使用以下代码来实现原型模式:

class Prototype {
  public clone(): Prototype {
    return Object.assign({}, this);
  }
}

class ConcretePrototype extends Prototype {
  public field1: string;
  public field2: number;

  public constructor(field1: string, field2: number) {
    this.field1 = field1;
    this.field2 = field2;
  }
}

const prototype = new ConcretePrototype("Hello", 10);
const clone = prototype.clone();

console.log(clone.field1); // Output: Hello
console.log(clone.field2); // Output: 10

结论

创建型设计模式是软件设计中非常重要的一个方面,它们可以使你的代码更加灵活、可扩展和易于维护。在 TypeScript 中,你可以使用这些设计模式来构建更加健壮和可维护的代码。我希望这篇文章对你有帮助,如果你有任何问题,请随时留言给我。