一、简介
策略模式:定义一族算法类,将每个算法分别封装起来,让它们可以互相替换。策略模式可以使算法的变化独立于使用它们的客户端(这里的客户端代指使用算法的代码)。
二、适用场景
- 动态选择算法
- 多种类似的行为
三、UML类图
四、案例
根据成年人、青年、小孩的不同计算不同的价格。
package main
import "fmt"
type PricingStrategy interface {
CalculatePrice(price float64) float64
}
type ChildrenPricingStrategy struct {
}
func NewChildrenPricingStrategy() *ChildrenPricingStrategy {
return &ChildrenPricingStrategy{}
}
func (s *ChildrenPricingStrategy) CalculatePrice(price float64) float64 {
return price * 0.5
}
type AdultPricingStrategy struct {
}
func NewAdultPricingStrategy() *AdultPricingStrategy {
return &AdultPricingStrategy{}
}
func (s *AdultPricingStrategy) CalculatePrice(price float64) float64 {
return price
}
type SeniorPricingStrategy struct {
}
func NewSeniorPricingStrategy() *SeniorPricingStrategy {
return &SeniorPricingStrategy{}
}
func (s *SeniorPricingStrategy) CalculatePrice(price float64) float64 {
return price * 0.8
}
type PriceCalculator struct {
Strategy PricingStrategy
}
func NewPriceCalculator(strategy PricingStrategy) *PriceCalculator {
return &PriceCalculator{Strategy: strategy}
}
func (pc *PriceCalculator) Calculator(price float64) float64 {
return pc.Strategy.CalculatePrice(price)
}
func main() {
calculator := NewPriceCalculator(NewChildrenPricingStrategy())
fmt.Printf("Children price: %v\n", calculator.Calculator(100))
calculator = NewPriceCalculator(NewAdultPricingStrategy())
fmt.Printf("Adult price: %v\n", calculator.Calculator(100))
calculator = NewPriceCalculator(NewSeniorPricingStrategy())
fmt.Printf("Senior price: %v\n", calculator.Calculator(100))
}