JavaScript – State Pattern

GitHub Code


The state pattern changes how an object behaves based on changes in its internal state.  This object seems to ‘magically’ change.

More specifically, a state variable is held in a class called the ‘context’.  The state inside the context is updated by concrete implementations of a state interface.
To run:
•    Make Get Call
Screen Shot 2017-05-06 at 6.10.58 PM
•    Review output – In this sample, my context’s state moves from undefined to state 1, 2, 3, 4 and finally 5.

Screen Shot 2017-05-06 at 6.52.17 PM

I chose to implement the pattern’s defined components (see reference #1) with the following modules:

•    Context – Context.js has a reference to a state object and a method to return the current state.

Screen Shot 2017-05-06 at 6.52.43 PM
•    State Base -AbsStateBase.js which has the method execute that is implemented by each concrete State object.  It takes the context as an argument.

Screen Shot 2017-05-06 at 6.56.31 PM
•    Concrete Implementations (created in stateDriver.js)
⁃  Each implementation sets the state of the context to itself.  States go from undefined to state 5.

Screen Shot 2017-05-06 at 6.52.28 PM

This being JavaScript, the normal Object Oriented approaches don’t always work. So, I am doing my initialization a little differently.  More specifically:
▪    Context is a class variable in stateDriver.js
▪    Context’s state is set directly as a variable instead of as a method.
Stay tuned!
References
1.    http://www.blackwasp.co.uk/State.aspx
2.    https://sourcemaking.com/design_patterns/state
3.    https://www.codeproject.com/Articles/509234/The-State-Design-Pattern-vs-State-Machine

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s