目的:根据不同策略来执行对象的相应操作
和工厂模式很像,不同点在于:
工厂模式是传入参数后创建对象,根据传入的参数写逻辑来判断应该创建什么类型的对象,模式的使用者调用对象统一的方法操作。 策略模式是模式的使用者必须先创建好对象,将该对象作为参数传进去,然后通过该对象调用相应的方法。设计场景如下:
吃饭的时候,我们有三种主食可以选,米饭、面包和苗条。golang实现代码:
package strategypatternimport "fmt"/*实体类接口*/type Staplefood interface { Eat()}type RiceStaplefood struct {}type NoodleStaplefood struct {}/*策略类*/type EatContext struct { staplefood Staplefood}type BreadStaplefood struct {}func (RiceStaplefood) Eat(){ fmt.Println("吃米饭")}func (NoodleStaplefood) Eat() { fmt.Println("吃面条")}func (BreadStaplefood) Eat() { fmt.Println("吃面包")}/*策略类操作方法*/func (context EatContext) EatFood(){ context.staplefood.Eat()}/*策略类构造函数*/func NewEatContext(staplefood Staplefood) *EatContext{ return &EatContext{ staplefood:staplefood, }}func Excute(){ eat := NewEatContext(new(RiceStaplefood)) eat.EatFood() eat = NewEatContext(new(NoodleStaplefood)) eat.EatFood() eat = NewEatContext(new(BreadStaplefood)) eat.EatFood()}