-
Notifications
You must be signed in to change notification settings - Fork 4
/
state.go
88 lines (74 loc) · 1.48 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package ch16
import (
"fmt"
)
// 不同状态
type State interface {
String() string
Handel(c *Context)
}
type Context struct {
state State
}
func NewContext(s State) *Context {
return &Context{
state: s,
}
}
func (c *Context) Request() {
c.state.Handel(c)
}
func (c *Context) String() string {
return c.state.String()
}
type BaseState struct {
v string
}
func (e *BaseState) Get() string {
return e.v
}
// 具体状态
type EnergyState struct {
v string
base *BaseState
}
func NewEnergeSate() *EnergyState {
// t := time.Date(0, 0, 0, 9, 0, 0, 0, time.Local).Format("15:04:05")
return &EnergyState{
base: &BaseState{
v: "精力充沛",
},
}
}
func (e *EnergyState) String() string {
return e.base.v
}
func (e *EnergyState) Handel(c *Context) {
fmt.Printf("state is %s ", c.state.String())
c.state = NewRestSate()
fmt.Printf("nextstate is %s\n", c.state.String())
}
type RestState struct {
base *BaseState
}
func NewRestSate() *RestState {
// t := time.Date(0, 0, 0, 9, 0, 0, 0, time.Local).Format("15:04:05")
return &RestState{
base: &BaseState{
v: "休息状态",
},
}
}
func (e *RestState) String() string {
return e.base.v
}
func (e *RestState) Handel(c *Context) {
//逻辑判断是否转换到下一状态 或者加入参数到下一个状态
fmt.Printf("state is %s ", c.state.String())
c.state = NewEnergeSate()
fmt.Printf("nextstate is %s\n", c.state.String())
}
func stateMain() {
context := NewContext(NewEnergeSate())
context.Request()
}