This website requires JavaScript.

设计模式在 TypeScript 中的应用 - 命令模式

2017.12.23 16:49字数 1518阅读 504喜欢 3评论 3

定义

将请求封装成对象,从而使你可用不同的请求对客户进行参数化。

实现

思路:

  • command 命令;
  • received 接收者,真正执行命令的对象;
  • invoker 调用者,使用命令对象的入口。

例子:

// 抽象命令类
abstract class Order {
  public abstract execute(): void
}

// buy 命令
class BuyStock extends Order {

  // 实例化时,实际执行命令
  public constructor (stock: Stock) {
    super()
    this.stock = stock
  }

  // 实际执行类
  private stock: Stock

  // 执行命令
  public execute (): void {
    this.stock.buy()
  }
}

// sell 命令
class SellStock extends Order {

  // 实例化时,实际执行命令
  public constructor (stock: Stock) {
    super()
    this.stock = stock
  }

  // 实际执行类
  private stock: Stock

  // 执行命令
  public execute (): void {
    this.stock.sell()
  }
}



// received 接收,真正的命令执行对象
class Stock {
  private name: string = 'ABC'
  private quantity: number = 10

  public buy (): void {
    console.log(`buy: ${this.name} ${this.quantity}`)
  }

  public sell (): void {
    console.log(`sell: ${this.name} ${this.quantity}`)
  }
}

// invoker 命令对象入口
class Broker {
  // 存储命令列表
  private orderList: Array<Order> = new Array<Order>()

  // 接受命令
  public takeOrder (order: Order): void {
    this.orderList.push(order)
  }

  // 执行命令
  public placeOrders (): void {
    for (let order of this.orderList) {
      order.execute()
    }
    this.orderList = new Array<Order>()
  }
}


const stock = new Stock()

const buysStock = new BuyStock(stock)
const sellStock = new SellStock(stock)

const broke = new Broker()

broke.takeOrder(buysStock)
broke.takeOrder(sellStock)

broke.placeOrders()