话不多说直接贴代码干就完了
package main
import "fmt"
// 定义接口
type Transportation interface{
Go()
}
// 策略1
type Airplane struct {
}
func (r *Airplane) Go() {
fmt.Println("Airplane gogogo")
}
// 策略2
type Train struct {
}
func (r *Train) Go() {
fmt.Println("Train gogogo")
}
// 策略主体
type Travel struct {
strategy Transportation
}
func (r *Travel) SetStrategy(t Transportation) {
r.strategy = t
}
func (r *Travel) Go() {
r.strategy.Go()
}
// 调用
func main() {
goTravel("poor")
goTravel("rich")
}
func goTravel(userType string) {
travel := new(Travel)
switch userType {
case "rich":
travel.SetStrategy(&Airplane{})
travel.Go()
case "poor":
fallthrough
default:
travel.SetStrategy(&Train{})
travel.Go()
}
}