-
Notifications
You must be signed in to change notification settings - Fork 0
/
state.go
65 lines (52 loc) · 1.18 KB
/
state.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main
import (
"fmt"
)
/*
This pattern abstracts state-related behavior into separate state classes,
letting the original object delegate work to instance of these classes instead of handling it itself.
e.g. state machine
*/
//abstract state
type state interface {
handler(ctx *context)
}
//main object
type context struct {
state state
}
func NewContext() *context {
return &context{state: &defaultState{}}
}
func (c *context) SetState(state state) {
c.state = state
}
func (c *context) Handle() {
c.state.handler(c)
}
//concrete state 1
type defaultState struct{}
func (d *defaultState) handler(ctx *context) {
fmt.Println("current state: default")
ctx.SetState(&concreteStateA{})
}
//concrete state 2
type concreteStateA struct{}
func (d *concreteStateA) handler(ctx *context) {
fmt.Println("current state: concreteStateA")
ctx.SetState(&concreteStateB{})
}
//concrete state 3
type concreteStateB struct{}
func (d *concreteStateB) handler(ctx *context) {
fmt.Println("current state: concreteStateB")
ctx.SetState(&defaultState{})
}
func RunState() {
context := NewContext()
context.Handle()
context.Handle()
context.Handle()
context.Handle()
context.Handle()
}