首页 > 其他 > 详细

策略模式

时间:2015-04-17 01:00:07      阅读:283      评论:0      收藏:0      [点我收藏+]

    策略模式:定义算法族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。——《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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!