Golang设计模式之策略模式

Jackey Golang 2,104 次浏览 , , 没有评论

创建文件MM.go

package strategy

import "fmt"

type MMContext struct {
    Name        string
    Age         int
    paoStrategy MMStrategy
}

func NewMMContext(name string, age int, strategy MMStrategy) *MMContext {
    return &MMContext{name, age, strategy}
}

func (mm *MMContext) Pao() {
    mm.paoStrategy.Pao(mm)
}

type MMStrategy interface {
    Pao(*MMContext)
}

type Girl struct {
}

func (*Girl) Pao(ctx *MMContext) {
    fmt.Println("girl for world", ctx.Name)
}

type Women struct {
}

func (*Women) Pao(ctx *MMContext) {
    fmt.Println("women for function", ctx.Name)
}

main.go

package main

import "test/design/strategy"

func main() {
    //ctx := strategy.NewMMContext("marry", 18, &strategy.Girl{})
    ctx := strategy.NewMMContext("alis", 28, &strategy.Women{})
    ctx.Pao()
}

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Go