实现策略模式和模板方法模式示例,添加支付策略和烹饪流程,增强代码可读性
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
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("========= 策略模式结束 =========")
|
||||
}
|
||||
Reference in New Issue
Block a user