天天看點

【寒江雪】Go實作政策模式

Strategy Pattern

  政策模式在運作時動态地裝配算法行為到對象中。

  我們可以定義算法,封裝它們,動态地切換它們。

實作

type Operator interface{
    Apply(int,int)int
}

type Operation struct{
    Operator Operator
}

func (this *Operation)Operate(l,r int)int{
    return this.Operator.Apply(l,r)
}
           

  定義具體的對象

type Addition struct{}

func (Addition) Apply(lval, rval int) int {
    return lval + rval
}
           

  使用

func main() {
    operation := strategy.Operation{strategy.Addition{}}

    res  := operation.Operate)

    fmt.Println(res)
}
           

注意

  • 政策模式可以讓更換對象的内髒,而裝飾者模式可以更換對象的外表。

有錢的捧個錢場,沒錢的捧個人場。

出來混不容易。

【寒江雪】Go實作政策模式

繼續閱讀