Skip to content

Commit

Permalink
add state
Browse files Browse the repository at this point in the history
  • Loading branch information
senghoo committed Apr 5, 2016
1 parent 77e7b0a commit 2f4f567
Show file tree
Hide file tree
Showing 3 changed files with 129 additions and 0 deletions.
3 changes: 3 additions & 0 deletions 16_state/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# 状态模式

状态模式用于分离状态和行为。
96 changes: 96 additions & 0 deletions 16_state/state.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
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{}
}
30 changes: 30 additions & 0 deletions 16_state/state_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package state

func ExampleWeek() {
ctx := NewDayContext()
ctx.Today()
ctx.Next()
ctx.Today()
ctx.Next()
ctx.Today()
ctx.Next()
ctx.Today()
ctx.Next()
ctx.Today()
ctx.Next()
ctx.Today()
ctx.Next()
ctx.Today()
ctx.Next()
ctx.Today()
ctx.Next()
// Output:
// Sunday
// Monday
// Tuesday
// Wednesday
// Thursday
// Friday
// Saturday
// Sunday
}

0 comments on commit 2f4f567

Please sign in to comment.