Saturday 5 May 2012

State and Strategy patterns

The State and Strategy patterns are very similar to each other but their use is somewhat different.

The state pattern is a way of encapsulating the behaviour of each state an object goes through. The state pattern fits nicely to model the operation of an ATM machine.

The key difference is that the state pattern is used to identify "states" which an object goes through. Where as the strategy pattern encapsulates a behaviour of the object. The state classes can be aware of the other states. This raise the question of coupling. For a system that is dynamically changing, then having states "knowing" other states might be acceptable.

The strategy on the other hand is an isolated functional unit and there is no interaction between the strategies. The context can choose which strategy to use where as the state is changed by changes to the internal state of the object. The most obvious way to use the strategy pattern is with the factory method.

No comments:

Post a Comment