使用 TypeScript 实现建造者模式实现的一个案例:

我们使用建造者模式创建了一个 Order 对象,该对象包含客户名称、送货地址和一些商品。
Order 类表示订单,它接受一个 OrderBuilder 对象来构建自己。

// 产品类 - 订单
class Order {
  private customerName: string;
  private address: string;
  private items: Item[];

  constructor(builder: OrderBuilder) {
    this.customerName = builder.getCustomerName();
    this.address = builder.getAddress();
    this.items = builder.getItems();
  }

  printOrder(): void {
    console.log(`Order for ${this.customerName}`);
    console.log(`Shipping to: ${this.address}`);

    console.log('Items:');
    for (let i = 0; i < this.items.length; i++) {
      const item = this.items[i];
      console.log(`- ${item.name} x ${item.quantity} (${item.price})`);
    }
  }
}

OrderBuilder 类表示订单生成器,它提供了一些方法来设置订单的各个部分,并最终构建出一个完整的订单对象。

// 生成器类 - 订单生成器
class OrderBuilder {
  private customerName: string;
  private address: string;
  private items: Item[] = [];

  setCustomerName(customerName: string): OrderBuilder {
    this.customerName = customerName;
    return this;
  }

  setAddress(address: string): OrderBuilder {
    this.address = address;
    return this;
  }

  addItem(item: Item): OrderBuilder {
    this.items.push(item);
    return this;
  }

  getCustomerName(): string {
    return this.customerName;
  }

  getAddress(): string {
    return this.address;
  }

  getItems(): Item[] {
    return this.items;
  }

  build(): Order {
    if (!this.customerName || !this.address || this.items.length <= 0) {
      throw new Error('Invalid order.');
    }

    return new Order(this);
  }
}

Item 接口表示商品,它有两个具体实现类 Fruit 和 Food,分别表示水果和食品。

// 产品类 - 商品
interface Item {
  name: string;
  price: number;
  quantity: number;
}

// 具体产品类 - 水果
class Fruit implements Item {
  name: string;
  price: number;
  quantity: number;

  constructor(name: string, price: number, quantity: number) {
    this.name = name;
    this.price = price;
    this.quantity = quantity;
  }
}

// 具体产品类 - 食品
class Food implements Item {
  name: string;
  price: number;
  quantity: number;

  constructor(name: string, price: number, quantity: number) {
    this.name = name;
    this.price = price;
    this.quantity = quantity;
  }
}

客户端代码使用 OrderBuilder 来构建一个包含两个商品的订单,并输出它的详细信息。

// 客户端代码
const orderBuilder = new OrderBuilder();

const fruit1 = new Fruit('Apple', 2.5, 3);
const food1 = new Food('Burger', 5, 2);

const order = orderBuilder
  .setCustomerName('John')
  .setAddress('123 Main St.')
  .addItem(fruit1)
  .addItem(food1)
  .build();

order.printOrder();
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐