What is the difference between Strategy pattern and Visitor Pattern?

后端 未结 11 1492
灰色年华
灰色年华 2021-01-29 22:18

I have trouble understanding these two design patterns.

Can you please give me contextual information or an example so I can get a clear idea and be able to map the dif

相关标签:
11条回答
  • 2021-01-29 22:45

    Seems like the second graph is Visitor Pattern to me...Since for strategy pattern, the class contains data structure tends to be only one, no subclass(Or the subclass stays same behavior of this part). The strategy is for different operations on the same structure.

    0 讨论(0)
  • 2021-01-29 22:46

    The visitor is like a one-night stand - you create it when you call the accept function and then they get separated and the visitor can be cleaned from the memory, it doesn't take any room for the class that use it.

    The strategy is like a marriage - you create the object, it lives in the class that uses it, takes memory, has a room and makes itself a coffee in the morning :) . Of course they can get a divorce and switch to another class but that class would also live in its owner's context.

    Hope it helps you remember :)

    0 讨论(0)
  • 2021-01-29 22:49

    Their differences are :

    1. Motivation
    2. Intent
    3. Implementation

    Not sure what is gained from comparing two different things but compare Strategy to Visitor.

    What is same about the two to make one look for their differences?

    0 讨论(0)
  • 2021-01-29 22:50

    I'll try to make the shortest answer.

    The two patterns complement one another: for instance, you could use a visitor to change the strategies on all the nodes of a graph.

    0 讨论(0)
  • 2021-01-29 22:52

    If we look at the UML for these two patterns from the GoF book, we see they are nothing alike.

    Visitor:


    Strategy:


    Some important differences stand out from the diagrams.

    • Strategy is based on composition. Visitor has no composition relationship.
    • Strategy is based on coding to an interface. Visitor is based on coding to an implementation.
    • Strategy implements one operation in multiple ways. Visitor implements multiple operations.

    UML alone does not capture the different motivations driving these patterns.

    • Strategy is an object-oriented solution for languages without first-class functions. As modern languages adopt closures or lambdas, there is less need for the Strategy Pattern.
    • Visitor is an object-oriented solution for languages without pattern matching or multiple dispatch. As modern languages adopt these features, Visitor too becomes obsolete.
    0 讨论(0)
提交回复
热议问题