实现策略模式和模板方法模式示例,添加支付策略和烹饪流程,增强代码可读性

This commit is contained in:
2026-01-07 19:27:14 +08:00
parent 5fbbada4b7
commit e5be1b62c2
6 changed files with 268 additions and 0 deletions
+51
View File
@@ -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("========= 策略模式结束 =========")
}
+48
View File
@@ -0,0 +1,48 @@
package main
import "fmt"
/*
实例:
汤宝宝炒西红柿鸡蛋。
*/
// 抽象接口
type Dish interface {
PrepareIngredients()
Cook()
Serve()
}
// 模板方法
func DoCooking(dish Dish) {
fmt.Print("第一步:")
dish.PrepareIngredients()
fmt.Print("第二步:")
dish.Cook()
fmt.Print("第三步:")
dish.Serve()
}
// 具体实现
type TomatoEggDish struct{}
func (t *TomatoEggDish) PrepareIngredients() {
fmt.Println("准备西红柿和鸡蛋;")
}
func (t *TomatoEggDish) Cook() {
fmt.Println("炒西红柿和鸡蛋;")
}
func (t *TomatoEggDish) Serve() {
fmt.Println("装盘,西红柿鸡蛋炒好了。")
}
func main() {
fmt.Println("========== 模板方法模式 ==========")
dish := &TomatoEggDish{}
DoCooking(dish)
fmt.Println()
fmt.Println("======== 模板方法模式结束 ========")
}