策略(Strategy)模式是一种行为设计模式,它会将策略实现方案抽取到一组被称为策略的类中,调用方还是调用同一个对象,不需要关注实现细节,只需要在参数中指定所需的策略即可。
什么时候使用策略模式:
- 当一个对象需要提供不同的行为,而又不想在运行时修改对象时
- 当想在运行时选择不同的行为而又不想写大量的条件语句时
- 当为同一种行为准备了不同的算法时
比如,在直播场景中,创建直播时会设置直播的一些基本信息,比如直播间名称,简介,公告等。同时我们支持两种类型的创建:一是立即开始的“即时直播”;二是“预约直播”,即未来时间的开播计划,创建后不会马上开始直播,并且会有一些预约开播时间前的一些延时任务的处理。
现在我们需要将直播的基本信息与创建方法解耦,这样在运行时只管创建,根据策略自动调整创建方式。如果还有新的创建方式,不应该去修改直播基本信息。我们为不同的创建方式设置一个策略组,然后将每种创建方式都封装起来,使之有相同的接口。
示例代码:
package main
import "fmt"
// 策略接口
type CreateStrategyer interface {
Create(*Live)
}
// 直播基础信息
type Live struct {
RoomName string
CreateStrategy CreateStrategyer
}
func NewLive(roomName string, strategy CreateStrategyer) *Live {
return &Live{
RoomName: roomName,
CreateStrategy: strategy,
}
}
func (l *Live) Create() {
l.CreateStrategy.Create(l)
}
// 即时型直播创建策略接口实现
type Immediate struct{}
func (i *Immediate) Create(l *Live) {
fmt.Println("save live info in db and create live room")
}
// 预约型直播创建策略接口实现
type Scheduled struct{}
func (s *Scheduled) Create(l *Live) {
fmt.Println("save live info in db and create delay tasks")
}
func main() {
var strategy CreateStrategyer
// 即时型直播
strategy = &Immediate{}
live := NewLive("axiaoxin's live", strategy)
live.Create()
fmt.Println("-----")
// 预约型直播
strategy = &Scheduled{}
live = NewLive("axiaoxin's live 2023-04-26 20:00", strategy)
live.Create()
}
运行代码,输出结果:
save live info in db and create live room
-----
save live info in db and create delay tasks