标签:
策略模式:定义算法族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。——《HEAD FIRST 设计模式》
我的golang代码:
package strategy import ( "fmt" ) ///////////////////////////////////////// type FlyBehavior interface { Fly() } type QuackBehavior interface { Quack() } type Duck interface { FlyBehavior QuackBehavior } ////////////////////////////////////////// type FlyWithWings struct { } func (s *FlyWithWings) Fly() { fmt.Println("Fly with wings!") } type FlyNoWay struct { } func (s *FlyNoWay) Fly() { fmt.Println("Fly no way!") } type Quack struct { } func (s *Quack) Quack() { fmt.Println("Quack!") } type Squeak struct { } func (s *Squeak) Quack() { fmt.Println("Squeak!") } type MuteQuack struct { } func (s *MuteQuack) Quack() { fmt.Println("Mute quack!") } /////////////////////////////////////////// type MallardDuck struct { FlyBehavior QuackBehavior } func NewMallardDuck() *MallardDuck { ret := &MallardDuck{&FlyWithWings{}, &Quack{}} return ret } type RedHeadDuck struct { FlyBehavior QuackBehavior } func NewRedHeadDuck() *RedHeadDuck { ret := &RedHeadDuck{&FlyNoWay{}, &Quack{}} return ret } type RubberDuck struct { FlyBehavior QuackBehavior } func NewRubberDuck() *RubberDuck { ret := &RubberDuck{&FlyNoWay{}, &Squeak{}} return ret } type DecoyDuck struct { FlyBehavior QuackBehavior } func NewDecoyDuck() *DecoyDuck { ret := &DecoyDuck{&FlyNoWay{}, &MuteQuack{}} return ret }
标签:
原文地址:http://www.cnblogs.com/foolbread/p/4433630.html