What is the difference between Strategy design pattern and State design pattern?

前端 未结 19 1860
太阳男子
太阳男子 2020-12-02 04:06

What are the differences between the Strategy design pattern and the State design pattern? I was going through quite a few articles on the web but could not make out the dif

19条回答
  •  不思量自难忘°
    2020-12-02 04:39

    Strategy pattern is used when you have multiple algorithm for a specific task and client decides the actual implementation to be used at runtime.

    UML diagram from wiki Strategy pattern article:

    Key features:

    1. It's a behavioural pattern.
    2. It's based on delegation.
    3. It changes guts of the object by modifying method behaviour.
    4. It's used to switch between family of algorithms.
    5. It changes the behaviour of the object at run time.

    Refer to this post for more info & real world examples:

    Real World Example of the Strategy Pattern

    State pattern allows an object to alter its behaviour when its internal state changes

    UML diagram from wiki State pattern article:

    If we have to change the behavior of an object based on its state, we can have a state variable in the Object and use if-else condition block to perform different actions based on the state. State pattern is used to provide a systematic and lose-coupled way to achieve this through Context and State implementations.

    Refer to this journaldev article for more details.

    Key differences from sourcemaking and journaldev articles:

    1. The difference between State and Strategy lies with binding time. The Strategy is a bind-once pattern, whereas State is more dynamic.
    2. 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.
    3. 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.

提交回复
热议问题