Junior — Middle
What functions does the context perform in the state or command pattern?
sobes.tech AI
Answer from AI
In the 'State' and 'Command' patterns, the context acts as a controlling object that stores the current state or command and interacts with them.
For the State pattern:
- The context contains a reference to a state object that defines the current behavior.
- It delegates method calls to the state, allowing behavior to change dynamically when the state changes.
- It encapsulates the logic for switching between states.
For the Command pattern:
- The context can store and invoke command objects.
- It manages a queue or history of commands (e.g., for undo/redo).
- It separates the sender of the command from its execution.
Example in Go for the State pattern:
// State interface
type State interface {
Handle(c *Context)
}
// Context stores the current state
type Context struct {
state State
}
func (c *Context) SetState(s State) {
c.state = s
}
func (c *Context) Request() {
c.state.Handle(c)
}
// Concrete state
type ConcreteStateA struct{}
func (s *ConcreteStateA) Handle(c *Context) {
fmt.Println("State A handling request")
c.SetState(&ConcreteStateB{})
}
// Concrete state
type ConcreteStateB struct{}
func (s *ConcreteStateB) Handle(c *Context) {
fmt.Println("State B handling request")
c.SetState(&ConcreteStateA{})
}
The context manages states and delegates calls, ensuring flexible behavior.