Thursday, March 3, 2011

Strategy vs State Design Patterns.

1. State: Encapsulate interchangable behaviours and use delegation to decide which behaviour to use.
Strategy: Subclasses decide how to implement steps in an algorithm.
2. With State Pattern we have a set of behaviours encapsulated in state objects; at any time the context is delegating to one of those states. Over time, the current state changes across the set of state objecs to reflect the internal state of context, so the context's behaviour changes over time as well. The client usually knows very little, if anything about the state objects.
With Strategy, the client usually specifies the strategy object that the context is composed with. Now, while the pattern provides the flexibility to change the strategy object at runtime, often there is a strategy object that is most appropriate for a context object.
3. Think of the State Pattern as an alternative to putting lots of conditionals in your context; by encapsulating the behaviours within state objects, you can simply change the state object in context to change its behaviour.

No comments:

Post a Comment