Benefits and Consequences of Using State Pattern
Understand how the State pattern encapsulates state-specific behavior to simplify extensions and reduce conditional complexity in C programs. Learn the trade-offs, including code modularity and state sharing, to decide when this pattern best suits your development needs.
We'll cover the following...
We'll cover the following...
Extending the State Machine
One of the State pattern strengths is that it encapsulates all state-specific behavior, making the state machine easy to extend.
- Adding a new event: Supporting a new event implies extending the
WatchStatestructure with a declaration of another pointer to a function. To add a new default implementation of the event toWatchState.c, use the mechanism described above. This step protects existing code from changes; the only impact on the concrete states is on the states that intend to support the new event, which have to implement a function of the correct signature to handle it. - Adding a new state: The new, concrete state has to implement functions for all events supported in that state. The only existing code that needs to be changed is the state in which we’ll transition to the new state. Please note that the State pattern preserves