By: A.S. Ran
Published in: PLoPD2
Summary: Design and implementation of objects with complex, state-dependent representation and behavior, or "moods."
To make specification of behavior simpler, decompose each object with complex behavior by distributing its responsibilities among several simpler objects. When the complex object cannot be simply decomposed, when the complexity of its behavior is due to control, or when it has a number of abstract states, decompose the class into a cluster of state classes. If the complexity is due not to control but to processing, decompose each complex method separately.
When an object's behavior depends significantly on its state, it behaves as if it had moods. The complex behavior can usually be traced to a set of conditions. When the same conditions affect a number of behaviors, identifying these conditions with abstract states may simplify specification of the object's behavior. Abstract states are conditions that guarantee more specific behavior of an object. When the object's behavior depends on additional conditions, substates may be identified to guarantee simpler behavior in each substate.
When the current complex behavior of an object cannot be determined from the values of its attributes, it must be explicitly represented and tracked. Use an FSM to specify the tracking logic.
Reactive objects often respond to events and update the current state. To separate the reaction and the state transition, implement a state machine using dedicated transition methods for state classes. These transition methods can be called by the reactive methods.
Explicitly implementing state transitions may be inappropriate. To maintain the object-to-state relation without explicitly modeling state transitions, use Predicative State Classes to specify conditions for complex behaviors of an object.
When you have applied For Objects with MOODS, Use State Classes, the representation and behavior are jointly specified by a cluster of classes. Normally, each object is identified with one class that determines its representation and behavior. To allow an object to follow behavior specified by different classes in different states, delegate the service to different objects. A change in the object's state can be conceptualized as a change in its association to a collaborator object.
To allow one object in different states to reflect the behavior and attributes specified by different state classes, the object must be an instance of all these classes. This is the MOOD Alternator class. Its instances include the attributes needed in all states. Each method of the MOOD Alternator delegates to a method of the state class corresponding to the mood of the alternator's instance.
To create a generic classification mechanism to use with different, complex, and changing hierarchies of predicative state classes, sequentially apply the predicates of the leaf states to the object.