Saturday, April 2, 2022

SKP's GoF Design Patterns a Day - 08 - State

 [GitHub Repository for Code Samples]
https://github.com/sumithpuri/skp-code-marathon-phuket

Was going through the book ‘Head First Design Patterns’, came up with my own examples to understand them further. Try downloading the code and see if it helps you in comprehending these in a better way.
 
State Pattern [Sample Code]
State Pattern defines a way to maintain various steps or states of the same machine or class. The word machine comes to the mind easily, because it is the simplest example of a real-world scenario where there is a need for operating the same object in steps or set states, with the transition from one step to the next defined by a single action (or multiple actions).
 
Fig. 6 : State (BehavioralDesign Pattern - Class and Sequence Diagram 
[Source : Wikipedia]
 


The example attached is a very crude but helpful one, that of an OnlineShopping site. The limitation of the site being that at any given point only a single item can be purchased and processed. The various states during the purchase and processing are SelectionState, PurchaseState, AuthoriseState, AssembleState (optional) and DispatchState. Each of these states is processed and followed in a sequential manner. OnlineShopping maintains an instance variable of each of these states and also a currentState variable. The various state methods that exist within OnlineShopping are selection(), purchase(), authorise(), assemble() and dispatch(). When client calls these methods, the actual invocations are performed on the state implementation held in the currentState variable. All state implementations implement the State interface, which specifies the lifecycle methods.

ShoppingClient is the main class. Try adding your own states along with the required lifecycle method.

No comments: