-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathstate.go
71 lines (58 loc) · 1.13 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
package main
import "fmt"
import "os"
type TrafficLightState interface {
Exec(k *AContext) bool
Name() string
}
type FinishState struct{}
func (s *FinishState) Exec(k *AContext) bool {
fmt.Println("FINISHED !!!")
return false
}
func (s *FinishState) Name() string {
return "finish"
}
type EndState struct{}
func (s *EndState) Exec(k *AContext) bool {
if k.Exit == true {
k.CurrentState = &FinishState{}
return true
}
k.CurrentState = &Ask{}
return true
}
func (s *EndState) Name() string {
return "end"
}
type AContext struct {
CurrentState TrafficLightState
Number int
Exit bool
}
func (a *AContext) prntState() {
fmt.Println(">>", a.CurrentState.Name())
if a.CurrentState.Name() == "end" {
fmt.Println("")
}
}
type Ask struct{}
func (s *Ask) Exec(k *AContext) bool {
var n int
fmt.Print(">> ")
fmt.Fscanf(os.Stdin, "%v", &n)
if n == k.Number {
k.Exit = true
} else {
if n > k.Number {
fmt.Println(">> you number is greater")
} else {
fmt.Println(">> you number is lower")
}
}
k.CurrentState = &EndState{}
return true
}
func (s *Ask) Name() string {
return "guess the number ... "
}