状态模式

  • 它主要用来解决对象在多种状态转换时,需要对外输出不同的行为的问题。状态和行为是一一对应的,状态之间可以相互转换
  • 例如 抽奖活动有很多的状态和对应的行为
  • getter setter 直接进行转发到合适的行为

    代码实现

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    class State {
    tmp: string
    set store(state: string){
    if(this.tmp !== state){
    this.tmp = state
    }
    }
    get store(): string {
    return this.tmp
    }
    }

    class People {
    state: State
    constructor(state: State){
    this.state = state
    }
    }

    const state = new State()
    const people = new People(state)

    state.store = 1
    console.log(people.state.store)
    class State {
    tmp: string
    set store(state: string){
    if(this.tmp !== state){
    this.tmp = state
    }
    }
    get store(): string {
    return this.tmp
    }
    }

    class People {
    state: State
    constructor(state: State){
    this.state = state
    }
    }

    const state = new State()
    const people = new People(state)

    state.store = 1
    console.log(people.state.store)

参考链接