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

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

    The difference simply lies in that they solve different problems:

    • The State pattern deals with what (state or type) an object is (in) -- it encapsulates state-dependent behavior, whereas
    • the Strategy pattern deals with how an object performs a certain task -- it encapsulates an algorithm.

    The constructs for achieving these different goals are however very similar; both patterns are examples of composition with delegation.


    Some observations on their advantages:

    By using the State pattern the state-holding (context) class is relieved from knowledge of what state or type it is and what states or types that are available. This means that the class adheres to the open-closed design principle (OCP): the class is closed for changes in what states/types there are, but the states/types are open to extensions.

    By using the Strategy pattern the algorithm-using (context) class is relieved from knowledge of how to perform a certain task (-- the "algorithm"). This case also creates an adherence to the OCP; the class is closed for changes regarding how to perform this task, but the design is very open to additions of other algorithms for solving this task.
    This likely also improves the context class' adherence to the single responsibility principle (SRP). Further the algorithm becomes easily available for reuse by other classes.

提交回复
热议问题