52 lines
983 B
Go
52 lines
983 B
Go
package main
|
|
|
|
import "fmt"
|
|
|
|
/*
|
|
实例:
|
|
汤宝宝成为了收银员,消费者可以使用现金或者支付宝支付。
|
|
*/
|
|
|
|
type Strategy interface {
|
|
Pay(amount float64) string
|
|
}
|
|
|
|
type CashPayment struct{}
|
|
|
|
func (c *CashPayment) Pay(amount float64) string {
|
|
return fmt.Sprintf("使用现金支付了 %.2f 元", amount)
|
|
}
|
|
|
|
type AlipayPayment struct{}
|
|
|
|
func (a *AlipayPayment) Pay(amount float64) string {
|
|
return fmt.Sprintf("使用支付宝支付了 %.2f 元", amount)
|
|
}
|
|
|
|
type Context struct {
|
|
strategy Strategy
|
|
}
|
|
|
|
func (c *Context) SetStrategy(strategy Strategy) {
|
|
c.strategy = strategy
|
|
}
|
|
|
|
func (c *Context) Pay(amount float64) string {
|
|
return c.strategy.Pay(amount)
|
|
}
|
|
|
|
func main() {
|
|
fmt.Println("=========== 策略模式 ===========")
|
|
|
|
context := &Context{}
|
|
|
|
context.SetStrategy(&CashPayment{})
|
|
fmt.Println(context.Pay(100))
|
|
|
|
context.SetStrategy(&AlipayPayment{})
|
|
fmt.Println(context.Pay(200))
|
|
|
|
fmt.Println()
|
|
fmt.Println("========= 策略模式结束 =========")
|
|
}
|