策略模式:定义了算法族,分别封装起来,让它们之间可以相互替换,此模式让算法的变化独立于使用算法的客户。
package strategy
import "fmt"
type Duck struct {
FlyBehavior FlyBehavior
QuackBehavior QuackBehavior
}
func (duck *Duck) PerformFly() {
duck.FlyBehavior.Fly()
}
func (duck *Duck) PerformQuack() {
duck.QuackBehavior.Quack()
}
type FlyBehavior interface {
Fly()
}
type QuackBehavior interface {
Quack()
}
type FlyWithWings struct {
}
func (*FlyWithWings) Fly() {
fmt.Println("I am flying!")
}
type FlyNoWay struct {
}
func (*FlyNoWay) Fly() {
fmt.Println("I can not fly!")
}
type Quack struct {
}
type MuteQuack struct {
}
type Squeak struct {
}
func (*Quack) Quack() {
fmt.Println("Quack!")
}
func (*MuteQuack) Quack() {
fmt.Println("Silence!")
}
func (*Squeak) Quack() {
fmt.Println("Squeak!")
}
func NewDuckContext(flyBehavior FlyBehavior, quackBehavior QuackBehavior) *Duck {
return &Duck{
FlyBehavior:flyBehavior,
QuackBehavior:quackBehavior,
}
}