This website requires JavaScript.

设计模式在 TypeScript 中的应用 - 组合模式

2018.01.02 10:21字数 1694阅读 490喜欢 4评论 4

定义

组合模式用于表示具有层次结构的数据,使得我们对单个对象和组合对象的访问具有一致性。

这种模式创建了一个包含自己对象组的类。该类提供了修改相同对象组的方式。

实现

比较简单,直接看一个组织中员工层次结构的例子:

// 每个员工都具有名字,职位,薪水,下属职员(maybe)等属性
class Employee {
  private name: string
  private dept: string
  private salary: number
  // 下属职员
  private subordinates: Employee[] = new Array<Employee>()

  constructor (name: string, dept: string, sal: number) {
    this.name = name
    this.dept = dept
    this.salary = sal
  }

  // 添加下属职员
  public add (e: Employee) {
    this.subordinates.push(e)
  }

  // 移除下属职员
  public remove (e: Employee) {
    const ind = this.subordinates.findIndex(item => item === e)
    if (ind) this.subordinates.splice(ind, 1)
  }

  // 获取员工列表
  public getSubordinates (): Employee[] {
    return this.subordinates
  }


  public toString (): string {
    return (`Employee: [
          Name: ${this.name},
          Dept: ${this.dept},
          Salary: ${this.salary}
        ]`)
  }
}

const CEO = new Employee('John','CEO', 30000)

const headSales = new Employee('Robert','Head Sales', 20000)

const headMarketing = new Employee('Michel','Head Marketing', 20000)

const clerk1 = new Employee('Laura','Marketing', 10000)
const clerk2 = new Employee('Bob','Marketing', 10000)

const salesExecutive1 = new Employee('Richard','Sales', 10000)
const salesExecutive2 = new Employee('Rob','Sales', 10000)

CEO.add(headSales)
CEO.add(headMarketing)

headSales.add(salesExecutive1)
headSales.add(salesExecutive2)

headMarketing.add(clerk1)
headMarketing.add(clerk2)

console.log(CEO.getSubordinates())
for(const person of CEO.getSubordinates()){
  console.log(person)
  for(const nextPerson of person.getSubordinates()){
      console.log(' \t ' + nextPerson)
  }
}