State Pattern

State Pattern

A recent post for JenkinsGadget had some ugly coding that I want to clean up. There’s too much conditional logic to determine and change the state of the program. This is where the State design pattern helps. It consolidates changes to state based on conditions.

State Pattern

A state pattern contains several classes:

  • Abstract state class
  • Concrete state classes
  • A context (or monitor) class

The concrete classes contain the logic needed to change the state of the data contained in the abstract class. The monitor class simply calls methods on the state object to update state.

JenkinsGadget needs to respond to changes based on the return value of a web service call. That state is used to change color and blink LEDs.

I created a state pattern demo solution in a my StatePatternDemo GitHub repository.

 

Share this Post