Tuesday, November 20, 2012

State pattern



  • State Design Pattern


Intent

    Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
    An object-oriented state machine
    wrapper + polymorphic wrappee + collaboration


Example


The State pattern allows an object to change its behavior when its internal state changes. This pattern can be observed in a vending machine. Vending machines have states based on the inventory, amount of currency deposited, the ability to make change, the item selected, etc. When currency is deposited and a selection is made, a vending machine will either deliver a product and no change, deliver a product and change, deliver no product due to insufficient currency on deposit, or deliver no product due to inventory depletion.


Rules of thumb

    State objects are often Singletons.
    Flyweight explains when and how State objects can be shared.
    Interpreter can use State to define parsing contexts.
    Strategy has 2 different implementations, the first is similar to State. The difference is in binding times (Strategy is a bind-once pattern, whereas State is more dynamic).
    The structure of State and Bridge are identical (except that Bridge admits hierarchies of envelope classes, whereas State allows only one). The two patterns use the same structure to solve different problems: State allows an object’s behavior to change along with its state, while Bridge’s intent is to decouple an abstraction from its implementation so that the two can vary independently.
    The implementation of the State pattern builds on the Strategy pattern. The difference between State and Strategy is in the intent. With Strategy, the choice of algorithm is fairly stable. With State, a change in the state of the “context” object causes it to select from its “palette” of Strategy objects.

http://sourcemaking.com/design_patterns/state




  • State pattern

The state pattern, which closely resembles Strategy Pattern, is a behavioral software design pattern, also known as the objects for states pattern. This pattern is used in computer programming to represent the state of an object. This is a clean way for an object to partially change its type at runtime
http://en.wikipedia.org/wiki/State_pattern

No comments:

Post a Comment