dushaoshuai / dushaoshuai.github.io

https://www.shuai.host
0 stars 0 forks source link

Strategy #71

Open dushaoshuai opened 1 year ago

dushaoshuai commented 1 year ago

简单说就是不同类型实现同一个接口,客户代码操作接口而不是与实现接口的具体类型交互,客户代码可以在运行时决定要使用的具体实现。

一个简单例子

strategy.go

package strategy

type Strategy interface {
    Execute(int, int) int
}

type Add struct{}

func (s *Add) Execute(a, b int) int {
    return a + b
}

type Subtract struct{}

func (s *Subtract) Execute(a, b int) int {
    return a - b
}

type Multiply struct{}

func (s *Multiply) Execute(a, b int) int {
    return a * b
}

type Context struct {
    strategy Strategy
}

func NewContext(strategy Strategy) *Context {
    return &Context{strategy: strategy}
}

func (c *Context) SetStrategy(strategy Strategy) {
    c.strategy = strategy
}

func (c *Context) ExecuteStrategy(a, b int) int {
    return c.strategy.Execute(a, b)
}

client.go

func ExampleStrategy() {
    c := strategy.NewContext(&strategy.Add{})
    fmt.Println(c.ExecuteStrategy(3, 4))

    action := "subtraction" // user's desired action
    switch action {
    case "addition":
        c.SetStrategy(&strategy.Add{})
    case "subtraction":
        c.SetStrategy(&strategy.Subtract{})
    case "multiplication":
        c.SetStrategy(&strategy.Multiply{})
    }
    fmt.Println(c.ExecuteStrategy(4, 5))

    // Output:
    // 7
    // -1
}

See also