Golang strategy design pattern

Objective: to perform a corresponding operation according to different strategies objects

And like factory mode, except that:

Factory pattern is to create an object after passing parameters, write logic based on the passed parameters to determine what type of object should be created, unified object method call to user mode operation.

Strategy mode is the mode the user must first create a good object, the object is passed as a parameter in, and then call the appropriate method by which an object.

Design scenario is as follows:

Dinner, we can choose three staple food, rice, bread and noodles.

golang Code:

package main

import "fmt"

// 定义类接口
type StapleFood interface {
	Eat()
}

// 定义接口实现类 1
type RiceStapleFood struct{}

// 定义接口实现类 2
type NoodleStapleFood struct{}

// 定义接口实现类 3
type BreadStapleFood struct{}

// 策略类
type ContextEat struct {
	stapleFood StapleFood
}

// 实现类1, 方法实现
func (f *RiceStapleFood) Eat() {
	fmt.Println("米饭")
}

// 实现类2, 方法实现
func (f *NoodleStapleFood) Eat() {
	fmt.Println("面条")
}

// 实现类3, 方法实现
func (f *BreadStapleFood) Eat() {
	fmt.Println("面包")
}

// 策略类方法实现
func (c *ContextEat) EatFood() {
	c.stapleFood.Eat()
}

// 策略类构造方法
func NewContextEat(s StapleFood) *ContextEat {
	return &ContextEat{stapleFood: s}
}

func main() {
	// 测试
	eat01 := NewContextEat(new(RiceStapleFood))
	eat01.EatFood()
	eat02 := NewContextEat(new(NoodleStapleFood))
	eat02.EatFood()
	eat03 := NewContextEat(new(BreadStapleFood))
	eat03.EatFood()
}

Guess you like

Origin www.cnblogs.com/zhichaoma/p/12640950.html