implemented state pattern
This commit is contained in:
parent
0580ec9c6e
commit
0627e4101c
@ -21,6 +21,7 @@
|
|||||||
- [Chain of responsibility](#chain-of-responsibility)
|
- [Chain of responsibility](#chain-of-responsibility)
|
||||||
- [Strategy](#strategy)
|
- [Strategy](#strategy)
|
||||||
- [Observer](#observer)
|
- [Observer](#observer)
|
||||||
|
- [State](#state)
|
||||||
- [Concurrency patterns](#concurrency-patterns)
|
- [Concurrency patterns](#concurrency-patterns)
|
||||||
|
|
||||||
---
|
---
|
||||||
@ -82,5 +83,8 @@ Strategy lets the algorithm vary independently from clients that use it.
|
|||||||
### Observer
|
### Observer
|
||||||
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically
|
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically
|
||||||
|
|
||||||
|
### State
|
||||||
|
Allow an object alter its behavior when its internal state changes. The object will appear on change its class
|
||||||
|
|
||||||
## Concurrency patterns
|
## Concurrency patterns
|
||||||
Pattenrs for concurrent work and parallel execution in Go.
|
Pattenrs for concurrent work and parallel execution in Go.
|
||||||
|
55
behavioral/state/state.go
Normal file
55
behavioral/state/state.go
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
package state
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
)
|
||||||
|
|
||||||
|
type State interface {
|
||||||
|
executeState(c *Context)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Context struct {
|
||||||
|
StepIndex int
|
||||||
|
StepName string
|
||||||
|
Current State
|
||||||
|
}
|
||||||
|
|
||||||
|
type StartState struct{}
|
||||||
|
|
||||||
|
func (s *StartState) executeState(c *Context) {
|
||||||
|
c.StepIndex = 1
|
||||||
|
c.StepName = "start"
|
||||||
|
c.Current = &StartState{}
|
||||||
|
}
|
||||||
|
|
||||||
|
type InprogressState struct{}
|
||||||
|
|
||||||
|
func (s *InprogressState) executeState(c *Context) {
|
||||||
|
c.StepIndex = 2
|
||||||
|
c.StepName = "inprogress"
|
||||||
|
c.Current = &InprogressState{}
|
||||||
|
}
|
||||||
|
|
||||||
|
type StopState struct{}
|
||||||
|
|
||||||
|
func (s *StopState) executeState(c *Context) {
|
||||||
|
c.StepIndex = 3
|
||||||
|
c.StepName = "stop"
|
||||||
|
c.Current = &StopState{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func StateDemo() {
|
||||||
|
context := &Context{}
|
||||||
|
|
||||||
|
startState := &StartState{}
|
||||||
|
startState.executeState(context)
|
||||||
|
fmt.Println("state: ", context)
|
||||||
|
|
||||||
|
inprState := &InprogressState{}
|
||||||
|
inprState.executeState(context)
|
||||||
|
fmt.Println("state: ", context)
|
||||||
|
|
||||||
|
stopState := &StopState{}
|
||||||
|
stopState.executeState(context)
|
||||||
|
fmt.Println("state: ", context)
|
||||||
|
}
|
Reference in New Issue
Block a user