设计模式
在这里插入图片描述
策略模式
策略模式定义一组算法类,将每个算法分别封装起来,让他们可以相互替换,策略模式可以使得算法独立于客户端,策略模式用来解耦策略的定义,创建,使用。一般来说策略模式也是包含 定义,创建,和使用 三个部分。
策略模式和工厂模式有点类似,只是多了策略这一部分,
运用场景
- 策略模式最常用的场景是,利用它来避免冗长的
if-else
或者 switch 分支判断 - 它的作用不止如此,可以跟模板模式一样,提供框架的扩展点。
- 策略模式的主要作用是解耦策略的定义,创建,使用,控制代码的复杂度
代码
package strategy
import "fmt"
type Payment struct {
context *PaymentContext
strategy PaymentStrategy
}
type PaymentContext struct {
Name, CardID string
Money int
}
func NewPayment(name, cardid string, money int, strategy PaymentStrategy) *Payment {
return &Payment{
context: &PaymentContext{
Name: name,
CardID: cardid,
Money: money,
},
strategy: strategy,
}
}
func (p *Payment) Pay() {
p.strategy.Pay(p.context)
}
type PaymentStrategy interface {
Pay(*PaymentContext)
}
type Cash struct{}
func (*Cash) Pay(ctx *PaymentContext) {
fmt.Printf("Pay $%d to %s by cash", ctx.Money, ctx.Name)
}
type Bank struct{}
func (*Bank) Pay(ctx *PaymentContext) {
fmt.Printf("Pay $%d to %s by bank account %s", ctx.Money, ctx.Name, ctx.CardID)
}
测试
package strategy
func ExamplePayByCash() {
payment := NewPayment("Ada", "", 123, &Cash{})
payment.Pay()
// Output:
// Pay $123 to Ada by cash
}
func ExamplePayByBank() {
payment := NewPayment("Bob", "0002", 888, &Bank{})
payment.Pay()
// Output:
// Pay $888 to Bob by bank account 0002
}
在这里插入图片描述
欢迎关注公众号:程序员开发者社区
关注我们,了解更多
参考资料
- https://github.com/senghoo/golang-design-pattern