Patterns in User Interface programming

User interface components represent state of the user who interacts with it.

In UI programming, its a good practise to seperate UI components from the state they represent.

If we seperate state from UI components, how do we enable communication between them?. There are two well defined patterns that help us to enable communication between UI components and their state.

  1. Command pattern
  2. Observer pattern

Command pattern : Making a state change

UI component will not make a change to state, directly. It will send a command (with any other details as command payload) about new state it wants to be in , to a controller. Controller will have access to the state, knows how to transition to a new state, from commands it receive. Controller make appropriate changes to the state based on commands and its payload.

Observer pattern : Observing changes in state

How does UI component know about change in state?. UI components shall register to observe changes in state. When state changes, UI components get notification about the change and UI components react to the change.