In: Computer Science
Compare the State Pattern and the Strategy Pattern. What is the main difference? Explain their uses and provide an example of where you would use the State Pattern
`Hey,
Note: Brother if you have any queries related the answer please do comment. I would be very happy to resolve all your queries.
Strategy design pattern in Java is used to encapsulate related
set of algorithms to provide runtime flexibility to client. Client
can choose any algorithm at runtime, without changing Context
class, which uses Strategy object. Some of the popular example of
Strategy pattern is writing code, which uses algorithms e.g.
encryption, compression or sorting algorithm.
On the other hand, State design pattern allows an object to behave
differently at different state. Since real world object often has
state, and they behave differently at different state, e.g. a
Vending Machine only vend items if it's in hasCoin state, it will
not vend until you put the coin on it.
You can now clearly see the difference between Strategy and
State pattern, there intent is different. State pattern helps
object to manage state, while Strategy pattern allows client to
choose different behaviour. Another difference, which is not easily
visible is, who drives change in behaviour.
In case of Strategy pattern, it's client, which provides different
strategy to Context, on State pattern, state transition is managed
by Context or State itself. Also, if you are managing state
transition in State object itself, it must hold reference of
Context e.g. Vending Machine, so that it can call setState() method
to change current state of Context.
On the other hand, Strategy object never held reference of Context,
it's client which passes Strategy of there choice to Context.
Kindly revert for any queries
Thanks.