[设计模式 Go实现] 行为型~状态模式

2024-01-03 09:07:01

状态模式用于分离状态和行为。

state.go
package state

import "fmt"

type Week interface {
    Today()
    Next(*DayContext)
}

type DayContext struct {
    today Week
}

func NewDayContext() *DayContext {
    return &DayContext{
        today: &Sunday{},
    }
}

func (d *DayContext) Today() {
    d.today.Today()
}

func (d *DayContext) Next() {
    d.today.Next(d)
}

type Sunday struct{}

func (*Sunday) Today() {
    fmt.Printf("Sunday\n")
}

func (*Sunday) Next(ctx *DayContext) {
    ctx.today = &Monday{}
}

type Monday struct{}

func (*Monday) Today() {
    fmt.Printf("Monday\n")
}

func (*Monday) Next(ctx *DayContext) {
    ctx.today = &Tuesday{}
}

type Tuesday struct{}

func (*Tuesday) Today() {
    fmt.Printf("Tuesday\n")
}

func (*Tuesday) Next(ctx *DayContext) {
    ctx.today = &Wednesday{}
}

type Wednesday struct{}

func (*Wednesday) Today() {
    fmt.Printf("Wednesday\n")
}

func (*Wednesday) Next(ctx *DayContext) {
    ctx.today = &Thursday{}
}

type Thursday struct{}

func (*Thursday) Today() {
    fmt.Printf("Thursday\n")
}

func (*Thursday) Next(ctx *DayContext) {
    ctx.today = &Friday{}
}

type Friday struct{}

func (*Friday) Today() {
    fmt.Printf("Friday\n")
}

func (*Friday) Next(ctx *DayContext) {
    ctx.today = &Saturday{}
}

type Saturday struct{}

func (*Saturday) Today() {
    fmt.Printf("Saturday\n")
}

func (*Saturday) Next(ctx *DayContext) {
    ctx.today = &Sunday{}
}
state_test.go
package state

func ExampleWeek() {
    ctx := NewDayContext()
    todayAndNext := func() {
        ctx.Today()
        ctx.Next()
    }

    for i := 0; i < 8; i++ {
        todayAndNext()
    }
    // Output:
    // Sunday
    // Monday
    // Tuesday
    // Wednesday
    // Thursday
    // Friday
    // Saturday
    // Sunday
}

文章来源:https://blog.csdn.net/qq_45704048/article/details/135325015
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。