diff --git a/README.md b/README.md index 4b33677..9b6c671 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ - [Chain of responsibility](#chain-of-responsibility) - [Strategy](#strategy) - [Observer](#observer) + - [State](#state) - [Concurrency patterns](#concurrency-patterns) --- @@ -82,5 +83,8 @@ Strategy lets the algorithm vary independently from clients that use it. ### Observer 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 Pattenrs for concurrent work and parallel execution in Go. diff --git a/behavioral/state/state.go b/behavioral/state/state.go new file mode 100644 index 0000000..578a716 --- /dev/null +++ b/behavioral/state/state.go @@ -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) +}