concept
Allows an object to change its behavior when its internal state changes. Object appears to have modified its class
When to use
When a task has a large number of state-dependent conditional statements, and different logic needs to be executed under each condition
Composition of state patterns
Status: the Status is used to abstract the behavior of the Status behavior class. Context: The Status environment maintains the switching of the Status Status and displays different behaviors in different states. StatusObj: The Status behavior class implements the behavior of the Status interfaceCopy the code
The following is an example of different behaviors generated by Do method in two different states, namely working days and rest days
1. Define the Status interface
// Interfaces define behavior methods in various states
type Status interface {
Do()
}
Copy the code
2. Define StatusObj
Define the weekday and rest day structures respectively, and implement Status
// Define the workday structure and implement Status
type Workday struct{}
func (*Workday) Do(a) {
fmt.Println("Work hard")}// Define the rest day structure and implement Status
type Offday struct{}
func (*Offday) Do(a) {
fmt.Println("Happy Life")}Copy the code
3. Define the Context
// Define Context with nested Status
type Context struct {
Status
}
// Define the SetStatus method for state switching
func (c *Context) SetStatus(status Status) {
c.Status = status
}
Copy the code
4. Use as follows
context := Context{
&Workday{},
}
context.Do() // Print out hard work
context.SetStatus(&Offday{})// Switch to rest day
context.Do() // Print out happy life
context.SetStatus(&Workday{})// Switch to the working day state
context.Do() // Print out hard work
Copy the code