State pattern is a behavioral pattern in GoF because it allows to alter its behavior when a context's internal state changes. The pattern handles each state using a separate state object and the transition from one state to another that does not call for if-then statements. source: GoF overviewThink of State pattern as a finite state machine. State pattern encapsulates all possible concrete States objects into a Context object, and have a variable references the current State object of the context. The association from Context to State hierarchy is a 'basic aggregation' (as opposed to composition aggregation) which means the Part Class (State) instances can outlive its Whole Class (Context). Whenever a Request() method (e.g. insertCard(), rejectCard(), etc.) is called upon the Context to trigger state transition, the request is delegated to the current State of the context to handle via calling into Handle(context), through which, a State object access Context and transition Context’s current State to the next State after processing the requested action. All methods implemented by State are possible actions to be applied to the state, the target state to transition to is coded in the method as seen in the code example below. Alternatively, I've seen implementation of State class be initiated with a Context via constructor, so on delegating request, you'd call into State's Handle() without needing to pass it the Context (instead of calling Handle(context)). state design pattern code exampleContext class: public class ATMMachineContext { State: public interface ATMState { In Java, you may consider implementing states using enum, see "Java Secret: Using an enum to build a State machine." when to use state design pattern
comparisonState vs. Strategy
0 Comments
Leave a Reply. |
Categories
All
Archives
May 2020
|