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

前端 未结 19 1924
太阳男子
太阳男子 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:20

    This is a pretty old question, but still, I was also looking for the same answers and this is what I have discovered.

    For State pattern lets consider an example of Medial Player Play button. When we do play it starts playing and makes the context aware that it is playing. Every time the client wants to perform play operation he checks the current state of the player. Now the client knows the state of the object is playing via the context object so he calls the pause state objects actions method. The part of the client realizing the state and on what state it needs to do action can be automated.

    https://www.youtube.com/watch?v=e45RMc76884 https://www.tutorialspoint.com/design_pattern/state_pattern.htm

    In the case of Strategy pattern, the arrangement of the class diagram is same as state pattern. The client comes to this arrangement to do some operation. That is instead of the different states there are different algorithms say for example different analysis that needs to be performed on the pattern. Here the clients tell the context what it wants to do that what algorithm (business defined custom algorithm) and then performs that.

    https://www.tutorialspoint.com/design_pattern/strategy_pattern.htm

    Both implements open close principle so the developer has the capability to add new states to the state pattern and new algorithm.

    But the difference is what they are used that is state pattern used to execute different logic based on a state of the object. And in a case of strategy different logic.

提交回复
热议问题