![](https://img-blog.csdnimg.cn/direct/21126355d689452f932d333ae3e6392e.png)
十四、strategy 策略模式
https://refactoringguru.cn/design-patterns/strategy
需求: client 知道很多不同的策略, 希望在运行时切换.
场景示例: 就像高德地图一样, 导航到某地, 用户可选择其一: 地铁, 自驾, 打车, 自行车 等.
实现方式: 定义策略接口, 上层组合该接口. client 在运行时切换 具体策略.
14.1 map_app
├── mapapp.go
├── mapapp_test.go
└── navigate_strategy.go
14.1.1 map_app_test.go
package _41map_app
import "testing"
func TestMapApp(t *testing.T) {
app := MapApp{}
app.SetNavigateStrategy(&WalkNavigateStrategy{})
app.Run()
app.SetNavigateStrategy(&SubwayNavigateStrategy{})
app.Run()
app.SetNavigateStrategy(&TaxiNavigateStrategy{})
app.Run()
}
14.1.2 map_app.go
package _41map_app
import "fmt"
type MapApp struct {
navigateStrategy NavigateStrategy
}
func (app *MapApp) Run() {
fmt.Println("打开导航地图APP")
app.navigateStrategy.Navigate()
fmt.Println("关闭导航地图APP")
}
func (app *MapApp) SetNavigateStrategy(s NavigateStrategy) {
app.navigateStrategy = s
}
14.1.3 navigate_strategy.go
package _41map_app
import "fmt"
type NavigateStrategy interface {
// Navigate 导航
Navigate()
}
type WalkNavigateStrategy struct {
}
func (s *WalkNavigateStrategy) Navigate() {
fmt.Println("步行导航开始")
}
type SubwayNavigateStrategy struct {
}
func (s *SubwayNavigateStrategy) Navigate() {
fmt.Println("地铁导航开始")
}
type TaxiNavigateStrategy struct {
}
func (s *TaxiNavigateStrategy) Navigate() {
fmt.Println("出租车导航开始")
}