State Pattern — A Quick Guide
Design Patterns: State Pattern
2 min readDec 29, 2021
--
“State Pattern lets an object alter its behavior when its internal state changes.”
Simple Example:
Suppose you have a cell phone and it has three profiles for incoming calls:
Silent mode, vibrating mode and ringing mode.
Incoming call is always the same but how you receive it always changes.
Real-Life Example:
Suppose you have a website that has many pages.
It’s internal logic for dark mode & light mode is the same.
It would be the best if we could change the visibility with just a simple code block, keeping it abstract.
Implementation
public interface PageViewState {
void view();
}public class ViewStateContext {
private PageViewState currentState;
public ViewStateContext() {
currentState = new LightModeState(); // default
}
public void setState(PageViewState state) {
currentState = state;
} @Override
public void view() {
currentState.view(this);
}
}public class LightModeState implements PageState {
@Override
public void view(ViewStateContext ctx) {
// implementation
}
}public class DarkModeState implements PageState {
@Override
public void view(ViewStateContext ctx) {
// implementation
}
}
And the client code would be like:
ViewStateContext stateContext = new ViewStateContext();stateContext.view(); // shows pages in light mode
stateContext.view();stateContext.setState(new DarkModeState());stateContext.view(); // shows pages in dark mode
stateContext.view();
Voila!
Thank you for reading and being a part of my journey!
Reference(s)
- Dive into Design Patterns. by Alexander Shvets, Released 2019.