Pregunta

I was reading through this link about the state pattern. Is it looks like strategy pattern? What is the exact difference between these two patterns?

¿Fue útil?

Solución

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.

See http://sourcemaking.com/design_patterns/state

Otros consejos

Strategy Pattern is very similar to State Pattern. One of the difference is that Context contains state as instance variable and there can be multiple tasks whose implementation can be dependent on the state whereas in strategy pattern strategy is passed as argument to the method and context object doesn’t have any variable to store it.

for more details see Strategy design pattern in java example tutorial

I think one major difference is that:

-In State Pattern, we pass the context itself as a parameter to the method of the state concrete class we need to assign to the context and it do two things: at first it assigns itself to the sent context, Secondly, it performs its role.

-In Strategy Pattern, we pass the strategy to the context when we first create it, so it remains as it is for the whole program, unless we assign the same variable to a new context(pointer) in the memory using "new" and assign a new strategy to it, and after a while garbage collector would eliminate the old context with its assigned strategy.

More clearly, Strategy is fixed for one context and once assigned it cannot be changed, even the context does not have a strategy setter. But for State, many states can be assigned to the same context one after another, as the context has a setter for states.

I hope it is useful.

In a State pattern, usually an action of a state causes a change of state; in a strategy pattern, an action of a strategy does not causes a change of strategy. In other word, change of state lies in the state itself; change of strategy lies in external condition.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top