What is the difference between Strategy pattern and Visitor Pattern?

后端 未结 11 1597
灰色年华
灰色年华 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: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.

提交回复
热议问题