![]() To avoid duplication of similar code across multiple states, you may provide intermediate abstract classes that encapsulate some common behavior. These methods should make sense for all concrete states because you don’t want some of your states to have useless methods that will never be called.Ĭoncrete States provide their own implementations for the state-specific methods. The State interface declares the state-specific methods. The context exposes a setter for passing it a new state object. The context communicates with the state object via the state interface. Hence, a lean state machine built with a limited set of conditionals can grow into a bloated mess over time.Ĭontext stores a reference to one of the concrete state objects and delegates to it all state-specific work. It’s quite difficult to predict all possible states and transitions at the design stage. ![]() The problem tends to get bigger as a project evolves. Code like this is very difficult to maintain because any change to the transition logic may require changing state conditionals in every method. Most methods will contain monstrous conditionals that pick the proper behavior of a method according to the current state. The biggest weakness of a state machine based on conditionals reveals itself once we start adding more and more states and state-dependent behaviors to the Document class. Does the following code structure ring a bell? class Document is Even if you’ve never heard about finite-state machines before, you’ve probably implemented a state at least once. Usually, this “state” is just a set of values of the object’s fields. State machines are usually implemented with lots of conditional statements ( if or switch) that select the appropriate behavior depending on the current state of the object. Possible states and transitions of a document object. In Published, it doesn’t do anything at all.In Moderation, it makes the document public, but only if the current user is an administrator.In Draft, it moves the document to moderation.The publish method of the document works a little bit differently in each state: ![]() A document can be in one of three states: Draft, Moderation and Published. You can also apply this approach to objects. These switching rules, called transitions, are also finite and predetermined. However, depending on a current state, the program may or may not switch to certain other states. Within any unique state, the program behaves differently, and the program can be switched from one state to another instantaneously. ![]() The main idea is that, at any given moment, there’s a finite number of states which a program can be in. The State pattern is closely related to the concept of a Finite-State Machine Finite-State Machine. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |