State pattern

State pattern allows an object to alter its behavior when its internal state changes (a), the object would appear to change its class (b).
A context (e.g. a state machine) has an internal state and public action methods which have different behavior based on the internal state. The implementation of these methods could have switch/case statements based on the state but this solution would be hardly extensible. Instead of that we could copy the context’s public interface to the state interface and write concrete state classes implementing that state interface and providing implementation relevant for each state (ad a). Then when a request in made on the context, it delegates it to the method call on an appropriateĀ  state. Internally they will do the business logic and may change the state of the context.

The concrete classes are registered in the context and initial state is set (e.g. created and initialized in context constructor). The constructor of each of these classes takes a parameter a reference to the context, so that the context state can be changed.

As a result, a new state will be encapsulated into a new class and we will avoid extensive switch/case of if statements.

The composition of the state classes (registration) allows us to reference different state objects what looks like change a class (ad b).

By encapsulating each state into class, we localize any changes that have to be made. State transitions can be controlled by state classes or by context. State classes can be shared among context instances (make context classes final static, they shouldn’t have the any internal state).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s