What is the difference between Strategy pattern and Visitor Pattern?

后端 未结 11 1601
灰色年华
灰色年华 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条回答
  •  萌比男神i
    2021-01-29 22:25

    If you have just one single context or element and need to perform different operations on that context, then you can choose Strategy Pattern. This is the 1:M relationship mentioned in above answer. java.util.Comparator is a good example of Strategy design pattern in action. There we can have different sorting strategies for the same collection (context or element).

    On the other hand, say you have multiple elenents all complies to a common contract and need to perform different operations on each of them. For an example consider a car wash usecase where you have body, engine and wheel etc and each of which can be washed using either steam or water. That is a good use of Visitor Pattern. But make sure that your context elements stay intact and never changes. If the elements are going to change say adding a Door element to the Car, then you need to change all the Visitors adding one new method in each of them and violating OCP nature of the pattern. So, this is the M:N relationship stated in the above answer.

    If you are further interested in reading more about the subtle differences between the two Design Patterns, I suggest you reading this article.

提交回复
热议问题