A simple example of the State design pattern
Let's understand all three participants with a simple example. Say, we want to implement a TV remote with a simple button to perform on/off actions. If the TV is on, the remote button will switch off the TV and vice versa. In this case, the State
interface will define the method (say, doThis()
) to perform actions such as switching on/off the TV. We also need to define ConcreteClass
for different states. In this example, we have two major states, StartState
and StopState
, which indicate when the TV is switched on and the state in which the TV is switched off, respectively.
For this scenario, the TVContext
class will implement the State
interface and keep a reference to the current state. Based on the request, TVContext
forwards the request to ConcreteState
, which implements the actual behavior (for a given state) and performs the necessary action. So, in this case, the base state is StartState
(as defined earlier) and the request received...